Segmentation Fault Question

Sep 21, 2018 at 11:35pm
Currently working with pointers and from experience, I know that segfaults happen with the poor use of pointers, however, I'm not experienced enough to know why this one is happening. IF someone could explain it to me that would be very appreciated

it occurs at line 17

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  class Product {
public:
    char name[10];
    int quantity;
    
    Product(){
        strcpy(name, "none");
    }
};

int main() {
    Product *products[5];

    const string names[5] = {"mild", "medium" , "hot", "sweet", "zesty"};

    for(int i = 0; i < 5; i++){
        strcpy(products[i]->name, names[i].c_str());
    }
Last edited on Sep 21, 2018 at 11:35pm
Sep 22, 2018 at 3:22am
products is an array of pointers that point to... what memory exactly?
you need to loop over that array and allocate memory to each one using the 'new' statement. And every new needs a delete after you are done with it.
or, just make an array of product and drop the pointers.
Last edited on Sep 22, 2018 at 3:23am
Topic archived. No new replies allowed.