0

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

  • 我将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);
4

2 回答 2

2

@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);

它应该可以正常工作。

于 2013-03-11T15:33:26.027 回答
1

在 C 中,指针是按值传递的。如果您将指针传递给函数,然后在该函数中更改其值(它指向的对象的地址),它不会像 C++ 引用那样传播到原始指针。

在这里,将更改(being , or )malloc指向的地址,但仅限于本地。实际的,和(比如说)将保持未初始化状态。你的编译器可能会警告你。argabcabcmain

传递这些指针时使用双重间接:

split(buffer,3, &a, &b, &c);

...以及split函数中的正确代码,例如:

char **arg = va_arg ( arguments, char ** );
*arg = malloc(...);
// etc.
于 2013-03-11T15:36:52.963 回答