[英]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.