[英]Issue with for loop in C when using struct
我執行以下代碼從文本文件中讀取值。 文本文件看起來像這樣。(在代碼中它被命名為annotation.txt )
299.jpg
480
640
3
dog
124
234
380
290
hand
789
456
234
123
wire
900
567
456
234
這是代碼。
#include <stdio.h>
#include <stdlib.h>
typedef struct object
{
char obj_name[20];
int x_min;
int y_min;
int x_max;
int y_max;
} Object;
typedef struct annotation
{
char img_name[20];
int width;
int height;
int num_obj;
Object objects[];
} Annotation;
void readAnnotation(char *fileName, Annotation *annot);
int main()
{
Annotation annot;
readAnnotation("annotation.txt", &annot);
printf("%s\n", annot.img_name);
printf("%d\n", annot.width);
printf("%d\n", annot.height);
printf("%d\n", annot.num_obj);
printf("0th object name for the 1st time %s\n", annot.objects[0].obj_name); // here it can be seen as 'dog'
for (int i = 0; i < 3; i++)
{
printf("%s\n", annot.objects[i].obj_name); // oth one disappear
printf("%d\n", annot.objects[i].x_min);
printf("%d\n", annot.objects[i].y_min);
printf("%d\n", annot.objects[i].x_max);
printf("%d\n", annot.objects[i].y_max);
};
printf("0th object name for the 2nd time %s\n", annot.objects[0].obj_name); //here it disappear
};
void readAnnotation(char *fileName, Annotation *annot)
{
FILE *fp;
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("\nError: Cannot open file");
exit(1);
};
fscanf(fp, "%s", annot->img_name);
fscanf(fp, "%d", &(annot->width));
fscanf(fp, "%d", &(annot->height));
fscanf(fp, "%d", &(annot->num_obj));
for (int i = 0; i < annot->num_obj; i++)
{
fscanf(fp, "%s", annot->objects[i].obj_name);
fscanf(fp, "%d", &(annot->objects[i].x_min));
fscanf(fp, "%d", &(annot->objects[i].y_min));
fscanf(fp, "%d", &(annot->objects[i].x_max));
fscanf(fp, "%d", &(annot->objects[i].y_max));
};
fclose(fp);
};
當我運行代碼時,在 main() function 編寫的 for 循環內使annot.objects[0].obj_name消失。 當我在 for 循環之前檢查它時,該值可以被視為“狗”。 但是在 for 循環內和 for 循環之后,該值消失了。 誰能告訴我我的代碼的問題並給我一個正確的答案來解決這個問題。
objects
永遠不會被初始化。 您只是在寫垃圾 memory。 Object objects[];
不創建數組,它實際上創建了一個指向數組的指針,並且您需要為其分配 memory 。 如果你不這樣做,你只是在使用一個未初始化的指針,你的程序可能會也可能不會工作,或者可能會崩潰。 這是未定義的行為。
通常,這被聲明為Objects* objects
,以明確它實際上是一個指針並記住要分配。 Arrays 和指針通常可以互換,因此無需更改其他代碼。
在您的readAnnotation
循環之前:
annot->objects = calloc(annot->num_obj, sizeof(Object));
關於:
typedef struct annotation
{
char img_name[20];
int width;
int height;
int num_obj;
Object objects[];
} Annotation;
上面只為前 4 個字段分配空間,然后是一個指針,但是,沒有為數組 0f object
分配空間建議:使用malloc()
和/或realloc()
為 Z49754317994151AAC35 的實例分配Object
否則,任何對objects[x]
的引用都是未定義的行為可能導致段錯誤事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.