简体   繁体   English

结构分割错误的打印数组

[英]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. pic的处理已损坏并且非常混乱。

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. 同样initCar()的赋值没有意义,您在循环,而只是将相同的整数值(!) imagecount指针imagecount次,就没有数据被复制。

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: 因此,在initCar()您必须具有:

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 * . 但是,它的itsPic当然必须是const int *类型。

You need to pass itsPic as a pointer in initCar . 您需要将itsPic作为指针传递itsPic initCar If you're doing so, you don't need the for loop for the affectation. 如果这样做,则不需要for循环来实现效果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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