gpt4 book ai didi

c - 如何动态改变char指针大小?

转载 作者:行者123 更新时间:2023-11-30 15:51:20 25 4
gpt4 key购买 nike

我使用 realloc 来动态增加 char 指针 (*seqA) 的大小。还有其他更好的方法吗?

这是我的代码的一部分:

    while((holder=fgetc(fileA)) != EOF) {
lenA++;
temp=(char*)realloc(seqA,lenA*sizeof(char));
if (temp!=NULL) {
seqA=temp;
seqA[lenA-1]=holder;
}
else {
free (seqA);
puts ("Error (re)allocating memory");
exit (1);
}
}

最佳答案

由于您的代码将完整文件读入字符串,因此为什么不使用以下代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

....

struct stat buf;
fstat(fileno(fileA), &buf);
seqA = malloc(buf.st_size);
fread(seqA, buf.st_size, 1, fileA);

当然,您应该检查这些函数的返回值并采取适当的操作。

关于c - 如何动态改变char指针大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201224/

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