繁体   English   中英

M分配,重新分配和返回C中的指针

[英]Malloc, realloc, and returning pointers in C

因此,我试图从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函数在其第一个参数中找到其第二个参数的第一个匹配项。

因此,在这里,您必须找到一种从input[start]开始运行strchr的方法,将字符'<'作为第二个参数传递给它,并存储strchr找到的长度。 这样就为您分配了输出所需的长度。

  • 不要忘了最后的'\\0'字符。
  • 使用库函数将字符串从input复制到output

由于这是一项任务,您可能会自己找出其余的...

那是动态阅读:

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main(){
 int mem=270;
 char *str=malloc(mem);
 fgets(str,mem,stdin);
 while(str[strlen(str)-1]!='\n'){//checks if we ran out of space
    mem*=2;
    str=realloc(str,mem);//double the amount of space
    fgets(str+mem/2-1,mem/2+1,stdin);//read the rest (hopefully) of the line into the new space.
 }
 printf("%s",str);
}

您的输出必须以'\\ 0'结尾。 指针只是指向字符串开头的指针,没有长度,因此,如果没有“ \\ 0”(NUL)作为标记,则不知道结尾在哪里。

通常,您不想为每个新字符调用realloc。 通常,将malloc()输出作为输入的strlen(),然后在末尾对其进行一次realloc()更为有意义。

另外,您应该在每次重新分配它时将其大小加倍,而不是仅添加一个字节。 但这需要您在一个单独的变量中跟踪当前分配的长度,以便知道何时需要重新分配。

您可能会阅读strcspn函数,它可能比使用while循环更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM