首页 > 解决方案 > 打印结构分段错误的数组

问题描述

我正在尝试打印我的结构。我希望它显示:

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;
}

标签: c

解决方案


的处理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 *


推荐阅读