c - 打印结构分段错误的数组
问题描述
我正在尝试打印我的结构。我希望它显示:
id: BBB-188
brand: BMW
pic: 1 2 3.
现在结果是这样的:
id: BBB-188
name: BMW
Segmentation fault: 11.
有谁知道我的代码有什么问题?
#define MAX 10000
#define IDSIZE 11
#define BRANDSIZE 50
#define PICSIZE 10
typedef struct{
char id[IDSIZE+1];
char brand[BRANDSIZE+1];
int *pic;
} Car;
void printCar(Car *pCar,int carcount, int imagecount) {
printf("id: %s \n",pCar->id);
printf("brand: %s \n",pCar->brand);
for(int i=0; i< imagecount; i++){
printf("pic: %d \n",pCar->pic[i]);
}
}
Car initCar(char itsId[],char itsBrand[],int itsPic, int imagecount){
Car newCar;
strcpy(newCar.id, itsId);
strcpy(newCar.brand, itsBrand);
for (int i = 0; i < imagecount; i++){
newCar.pic = itsPic;
}
return newCar;
}
int main(void){
int carcount=0;
int imagecount=0;
int test[3]={1,2,3};
Car myCar = initCar("BBB-188","BMW", test, 3 );
carcount=1;
imagecount=3;
printCar(&myCar,carcount,imagecount);
return 0;
}
解决方案
的处理pic
被破坏并且非常混乱。
您似乎想将其表示为整数数组,但您不存储长度。因此它必须总是三个,但是你可以在结构中使用一个数组,即:
int pic[3];
代替
int *pic;
里面的赋值initCar()
也没有任何意义,你在循环,但只是将相同的整数值(!)分配给指针imagecount
时间,没有数据被复制。
如果您希望图片数组的长度真正可变,则必须存储长度并分配内存以保存数字。所以initCar()
你必须有:
newCar.pic = malloc(imagecount * sizeof *newCar.pic);
memcpy(newCar.pic, itsPic, imagecount * sizeof *newCar.pic);
但是itsPic
当然必须是 type const int *
。
推荐阅读
- c - 在while循环C之外访问变量
- bash - 如何配置 PATH 变量以便我可以在 CLI 上运行包?
- go - 使用 golang 处理非 utf8 输入
- javascript - 用于包含空格和其他字符的单词的 Javascript 正则表达式
- javascript - 你能用 React hooks 提前回来吗?
- javascript - Gijgo DateTimePicker 过去日期禁用
- python - 如何在 VTK 中选择特定的单元格元素
- javascript - 此页面存在错误。Acrobat 可能无法正确显示页面。kendo.drawing.exportPDF
- elasticsearch - match_phrase_prefix 不返回 match_phrase 得到的结果
- python - 无法更改 Django 中的用户的 is_active 状态