gpt4 book ai didi

c - 在C中访问数组内的结构体字段

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

我正在编写一个程序,该程序应该构建一个 SDL_Rect 数组。在 for 循环内,我将值分配给 SDL_Rect 的字段,并有一个指针数组指向以这种方式创建的每个矩形。这是我的代码:

SDL_Rect *rectangles[n];

for (i = 0; i <= n - 1; i++)
{
SDL_Rect *rect = NULL;
rect->w = random_int(min_size, max_size);
rect->h = random_int(min_size, max_size);
rectangles[i] = rect;
}

n、min_size和max_size都是从stdin读取的,这是random_int方法:

int random_int(int min, int max)
{
return min + rand() % (max + 1 - min);
}

每次我尝试运行代码时,都会在 for 循环中抛出“段错误:11”。这是为什么?

最佳答案

rect中分配内存,否则这是未定义的行为。您基本上取消了对 NULL 值的引用,这导致了 UB。

SDL_Rect *rect;

rect = malloc(sizeof(SDL_Rect));
if( rect == NULL){
fprintf(stderr,"%s","Error in malloc");
exit(1);
}

..
..
free(rect);

关于c - 在C中访问数组内的结构体字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47229468/

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