gpt4 book ai didi

c - 在C中的结构中填充动态数组

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

嗨,我想用数据填充一个结构,所以我编写了这段代码,但是当我尝试运行它时,它崩溃并关闭,我不知道为什么:

#include <stdio.h>
#include <stdlib.h>

struct rectangle{
float length ;
float width ;
};


void main()
{
printf("enter the size of both arrays \n");
int x ;
scanf("%d",&x);

struct rectangle *r ;
r = (int *) malloc(x*sizeof(int));
int j ;
for (j = 0 ; j < x ; j++){
printf("enter rectangle length \n");
scanf("%d",r[j].length);
printf("enter rectangle width \n");
scanf("%d",r[j].width);

}
printf("%d \n",max(r,x));


}

但是当我尝试运行它时,它崩溃了。

最佳答案

您正在分配一个 int 数据数组,但尝试将它当作一个 rectangle 数据数组来使用。两种类型的尺寸不同。

像这样分配你的数组:

struct rectangle* r = malloc(x*sizeof(struct rectangle));

澄清一下:

sizeof(int) != sizeof(struct rectangle)

此外,scanf 还需要一个指向您正在扫描的每个变量的指针。%d 是整数的格式说明符,但长度和宽度是 float 。

用途:

scanf("%f",&r[j].length);
scanf("%f",&r[j].width);

关于c - 在C中的结构中填充动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028139/

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