gpt4 book ai didi

c - C 中的 Malloc、realloc 和返回指针

转载 作者:行者123 更新时间:2023-11-30 18:57:19 25 4
gpt4 key购买 nike

所以我试图从 html 页面获取信息。我使用curl来获取html页面。然后我尝试解析html页面并将我需要的信息存储在字符数组中,但我不知道数组的大小应该是多少。请记住,这是一个分配,所以我不会给出太多代码,所以我应该动态分配内存,但由于我不知道它的大小,所以我必须继续使用 realloc 分配内存。函数内一切都很好,但是一旦返回,指针内就没有存储任何内容。这是代码。另外,如果有一些图书馆可以为我做这件事,并且您知道它,您能否将我链接到它,这将使我的生活变得更加轻松。谢谢!

char * parse(int * input)
{
char * output = malloc(sizeof(char));
int start = 270;
int index = start;
while(input[index]!='<')
{
output = realloc(output, (index-start+1)*sizeof(char));
output[index-start]=input[index];
index++;
}
return output;
}

最佳答案

strchr函数查找第二个参数在第一个参数中第一次出现的位置。

所以在这里你必须找到一种方法来运行 strchrinput[start] 开始,向其传递字符 '<'作为第二个参数并存储 strchr 的长度发现。然后,这将为您提供需要分配给输出的长度。

  • 不要忘记'\0'结尾处的字符。
  • 使用库函数从 input 复制字符串至output .

由于这是一项作业,因此您可能会自己找到其余的内容......

关于c - C 中的 Malloc、realloc 和返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562008/

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