gpt4 book ai didi

通过引用返回的 C 风格字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:18 26 4
gpt4 key购买 nike

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

  • 我将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com