gpt4 book ai didi

无法将超过 1 个值添加到 C 中动态创建的数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:53 24 4
gpt4 key购买 nike

我试图在 C 中创建一个动态递增的数组,但出于某种原因,我无法为数组的第一个元素以外的任何元素赋值。代码运行时,temp的值一直在变化,而val的内容只是一个地址和链表中第一个float的值。有任何想法吗?提前致谢!

//Initialise variables.
char buf[20]={0};
float temp=0;
int i=0;

//Create the initial array.
size_t size = sizeof(float)*10;
float* val = malloc(size);
if (val == NULL) {
fprintf(stderr, "Initial malloc failed\n");
exit(1);
}

//Open the file (a list of floats).
FILE *file;
file = fopen("/Users/cc756/Dropbox/C_ECG_PROJECT/ECG_Project/ECG_Project/dataStream", "r");

if (!file){
printf("Coulding find file.\n");
exit(1);
}

//Save the contents of the list to a float array.
while (fgets(buf,20, file)!=NULL){
temp = atof(buf);
if (temp != 0){
val[i] = temp;
i++;
if(i==size){
size *= 2;
float* val_temp = realloc(val,size);
if(val_temp == NULL){
printf("Realloc failed.\n");
}
else{
val = val_temp;
}
}
}
}

最佳答案

我想你的意思是

if ( i == size / sizeof( float ) ){

还有循环的逻辑

while (fgets(buf,20, file)!=NULL){
temp = atof(buf);
if (temp != 0){
val[i] = temp;
i++;
if(i==size){
size *= 2;
float* val_temp = realloc(val,size);
if(val_temp == NULL){
printf("Realloc failed.\n");
}
else{
val = val_temp;
}
}
}
}

如果 val_temp 被赋值为 NULL 是错误的,因为 i 增加了并且在循环的下一次迭代中这个语句

val[i] = temp;

导致未定义的行为。

关于无法将超过 1 个值添加到 C 中动态创建的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43209585/

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