通过引用返回的 C 风格字符串

标签 c c-strings

谁能告诉我为什么这段代码不起作用?

  • 我将 char * 指针传入我的拆分函数并拆分我的缓冲区。
  • 为传入的每个 arg (char *) 在堆上分配内存,
  • 然后将子字符串 strcpy 到这个新缓冲区中。
  • 一切正常,直到我从该方法返回并尝试打印任何变量。
  • 分段失败
void split(char * buffer, int num, ...)
{
  char* string;
  char* tofree;
  string = strdup(trim(buffer));

  if (string != NULL) {
    tofree = string;

    va_list arguments; 

    //Initializing arguments to store all values after num 
    va_start ( arguments, num );           

    int i = 0;
    for (i = 0; i < num; i++ )        
    {
        //Item is the final store place of the split substring
        char * arg = va_arg ( arguments, char *);

        //Split the strings, delimiter is space
        char * splitBuffer = strsep(&string, " ");

        //Allocate the buffer memory to store the splitBuffer
        arg  =  malloc(sizeof(char*)*strlen(splitBuffer));

        strcpy(arg ,splitBuffer);
        printf("Buffer [%s] -- [%s]n", buffer, arg);
    }
    va_end ( arguments ); // Cleans up the list


    free(tofree);
  }
}




        char * a;
        char * b;
        char * c;
        split(buffer,3,a,b,c);
        printf("Print A = %s B = %s C = %s\n", a,b,c);

最佳答案

我认为@tjameson 的意思是:

  void split(char * buffer, int num, ...)
  {
     char* string;
     char* tofree;
     string = strdup(trim(buffer));

     if (string != NULL)
     {
        tofree = string;

        va_list arguments; 

        //Initializing arguments to store all values after num 
        va_start ( arguments, num );           

        int i = 0;
        for (i = 0; i < num; i++ )        
        {
           //Item is the final store place of the split substring
           char ** arg = va_arg ( arguments, char **);

           //Split the strings, delimiter is space
           char * splitBuffer = strsep(&string, " ");

           //Allocate the buffer memory to store the splitBuffer
           *arg  =  malloc(sizeof(char*)*strlen(splitBuffer));

           strcpy(*arg ,splitBuffer);
           printf("Buffer [%s] -- [%s]\n", buffer, *arg);
        }
        va_end ( arguments ); // Cleans up the list

        free(tofree);
     }
  }


    char * a;
    char * b;
    char * c;
    split(buffer,3,&a,&b,&c);
    printf("Print A = %s B = %s C = %s\n", a,b,c);

它应该可以正常工作。

关于通过引用返回的 C 风格字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342361/

相关文章:

c - 对包含零件列表的文件进行 fseek 和 fread

c - 这个没有 libc 的 C 程序如何工作?

创建目录并将输出文件保存在该目录中

c - 试图在一个字符之后复制字符串的其余部分

C:动态大小的二维字符串数组

c - 如何将int与C中的队列进行比较?

c# - 交互式曲线图

c - fscanf 每隔一行返回一次

c++ - 如何将QString转换为char **

将 char** 转换为 char* 或 char