gpt4 book ai didi

c - 在 C 中为结构数组重新分配内存

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

我在使用结构数组时遇到问题。我需要逐行读取文本文件,并并排比较值。例如,“妈妈”会返回 2 ma , 1 am 因为你有妈妈。我有一个结构:

typedef struct{
char first, second;
int count;
} pair;

我需要为整个字符串创建一个结构数组,然后比较这些结构。我们还介绍了内存分配,因此我们必须为任何大小的文件执行此操作。这就是我真正遇到麻烦的地方。如何为结构数组正确地重新分配内存?这是我目前的主要内容(无法编译,显然有错误,这有问题)。

int main(int argc, char *argv[]){
//allocate memory for struct
pair *p = (pair*) malloc(sizeof(pair));
//if memory allocated
if(p != NULL){
//Attempt to open io files
for(int i = 1; i<= argc; i++){
FILE * fileIn = fopen(argv[i],"r");
if(fileIn != NULL){
//Read in file to string
char lineString[137];
while(fgets(lineString,137,fileIn) != NULL){
//Need to reallocate here, sizeof returning error on following line
//having trouble seeing how much memory I need
pair *realloc(pair *p, sizeof(pair)+strlen(linestring));
int structPos = 0;
for(i = 0; i<strlen(lineString)-1; i++){
for(int j = 1; j<strlen(lineSTring);j++){
p[structPos]->first = lineString[i];
p[structPos]->last = lineString[j];
structPos++;
}
}
}
}
}
}
else{
printf("pair pointer length is null\n");
}

如果有更好的方法,我很乐意改变周围的情况。我必须使用上面的结构,必须有一个结构数组,并且必须处理内存分配。这些是唯一的限制。

最佳答案

为结构数组分配内存就像为一个结构分配内存一样简单:

pair *array = malloc(sizeof(pair) * count);

然后您可以通过订阅“array”来访问每个项目:

array[0] => first item
array[1] => second item
etc

关于 realloc 部分,而不是:

pair *realloc(pair *p, sizeof(pair)+strlen(linestring));

(这在语法上是无效的,看起来像是 realloc 函数原型(prototype)和它同时调用的混合体),你应该使用:

p=realloc(p,[new size]);

事实上,你应该使用不同的变量来存储 realloc 的结果,因为在内存分配失败的情况下,它会返回 NULL,同时仍然保留已经分配的内存(然后你就会失去它在内存中的位置) .但是在大多数 Unix 系统上,当进行临时处理(不是一些繁重的任务)时,达到 malloc/realloc 返回 NULL 的程度在某种程度上是罕见的情况(您必须耗尽所有虚拟空闲内存)。仍然最好写:

pair*newp=realloc(p,[new size]);
if(newp != NULL) p=newp;
else { ... last resort error handling, screaming for help ... }

关于c - 在 C 中为结构数组重新分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10197219/

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