[英]C-style string returning by reference
谁能启发我为什么此代码不起作用?
char *
指针传递给我的split函数,然后将缓冲区分开。 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语言中, 指针由value传递 。 如果您将指针传递给函数,然后在该函数内更改其值-它指向的对象的地址-则它不会像C ++引用那样传播到原始指针。
在这里, malloc
将更改arg
指向的地址( a
, b
或c
),但仅在本地。 实际的a
, b
和c
(例如main
)将保持未初始化状态。 您的编译器可能会警告您。
传递这些指针时,请使用双向重定向:
split(buffer,3, &a, &b, &c);
...以及您的split
函数中的正确代码,例如:
char **arg = va_arg ( arguments, char ** );
*arg = malloc(...);
// etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.