谁能告诉我为什么这段代码不起作用?
- 我将
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);