在 C 中访问数组中的结构字段
accessing struct fields inside array in C
我正在编写一个程序,该程序应该构建 SDL_Rects 的数组。在 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 循环中抛出一个 "Segmentation Fault: 11"。
这是为什么?
在rect
中分配内存,否则是未定义的行为。您基本上是在取消引用导致 UB 的 NULL
值。
SDL_Rect *rect;
rect = malloc(sizeof(SDL_Rect));
if( rect == NULL){
fprintf(stderr,"%s","Error in malloc");
exit(1);
}
..
..
free(rect);
我正在编写一个程序,该程序应该构建 SDL_Rects 的数组。在 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 循环中抛出一个 "Segmentation Fault: 11"。 这是为什么?
在rect
中分配内存,否则是未定义的行为。您基本上是在取消引用导致 UB 的 NULL
值。
SDL_Rect *rect;
rect = malloc(sizeof(SDL_Rect));
if( rect == NULL){
fprintf(stderr,"%s","Error in malloc");
exit(1);
}
..
..
free(rect);