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