简体   繁体   中英

Printing array of struct Segmentation fault

I'm trying to print my struct. I want it to show:

id: BBB-188
brand: BMW
pic: 1 2 3. 

Right now the result is this:

id: BBB-188 
name: BMW 
Segmentation fault: 11.

Does anyone know what is wrong with my code?

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

The handling of pic is broken and very confusing.

You seem to want to represent it as an array of integers, but you don't store the length. Thus it has to be always three, but then you can just use an array in the structure, ie:

int pic[3];

instead of

int *pic;

Also the assignment inside initCar() makes no sense, you're looping but simply assigning the same integer value (!) to the pointer imagecount times, no data is being copied.

If you want the length of the picture array to really be variable, you must store the length and allocate memory for holding the numbers. So in initCar() you must have:

newCar.pic = malloc(imagecount * sizeof *newCar.pic);
memcpy(newCar.pic, itsPic, imagecount * sizeof *newCar.pic);

but then itsPic must of course be of type const int * .

You need to pass itsPic as a pointer in initCar . If you're doing so, you don't need the for loop for the affectation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM