[尝试拆分字符串并将其放入数组时收到错误消息

问题描述 投票:0回答:1

我正在尝试分割用户的输入并将每个定界符放在一个数组中。

由于某些原因,使用这里的代码,我收到一条错误消息:'称为对象类型'char * [10]'不是函数或函数指针'。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 10
#define SIZE 256

char *read_line(char *buf, size_t sz) {
  printf("> ");
  fgets(buf, sz, stdin);
  buf[strcspn(buf, "\n")] = 0;
  return buf;
}

void split(char *buf, char *split[], size_t max) {
  char *temp = strtok(buf, " ");

  for (int i = 0; split[0] != '\0'; i++) {
    strcpy(split[i], temp);
    temp = strtok(NULL, buf);
  }
}

int main(int argc, char **argv) {
  char *buf = malloc(SIZE);
  char *split[MAX];

  while(1) {
    char *input = read_line(buf, SIZE);
    split(input, split, MAX);
  }
}

任何帮助将不胜感激。

c arrays string split strtok
1个回答
0
投票

此声明在main外部块的范围内

char *split[MAX];

隐藏具有在文件作用域中声明的相同名称的函数。

例如,重命名数组

char *words[MAX];

函数split无效,至少是因为您试图在未分配的内存中复制字符串

strcpy(split[i], temp);

该函数可以通过以下方式查看

size_t split( char *buf, char *words[], size_t max ) 
{
    size_t n = 0;
    char *temp;

    if ( n < max && ( temp = strtok( buf, " \t" ) ) != NULL )
    {
        do
        {
            words[n] = temp;
        } while ( ++n < max && ( temp = strtok( NULL, " \t" ) ) != NULL );
    }

    return n;
}

主要可以写

int main( void ) 
{
    char *buf = malloc( SIZE );
    char *words[MAX];

    size_t n = split( read_line( buf, SIZE), words, MAX );

    for ( size_t i = 0; i < n; i++ ) puts( words[i] );

    free( buf );
}

这里是示范节目

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 10
#define SIZE 256

char * read_line( char *buf, size_t sz ) 
{
    printf("> ");
    fgets(buf, sz, stdin);
    buf[strcspn(buf, "\n")] = 0;

    return buf;
}

size_t split( char *buf, char *words[], size_t max ) 
{
    size_t n = 0;
    char *temp;

    if ( n < max && ( temp = strtok( buf, " \t" ) ) != NULL )
    {
        do
        {
            words[n] = temp;
        } while ( ++n < max && ( temp = strtok( NULL, " \t" ) ) != NULL );
    }

    return n;
}

int main(void) 
{
    char *buf = malloc( SIZE );
    char *words[MAX];

    size_t n = split( read_line( buf, SIZE), words, MAX );

    for ( size_t i = 0; i < n; i++ ) puts( words[i] );

    free( buf );

    return 0;
}

其输出可能看起来像

> Hello kindawg
Hello
kindawg
© www.soinside.com 2019 - 2024. All rights reserved.