Structure
struct products{
int id;
char* name;
int buy;
int sell;
int q;
};
Within my main I've delcared a vector of products
and have a for loop to assign the pointer name
a value as such
int main(){
struct products arr[5];
for(int i=0; i<5; i ){
scanf("%s", arr[i].name);
}
return 0;
}
Seems to work fine on the first iteration but when it moves onto the second one that's where it gives me a segmentation error. The only thing I could find on other resources for similar problems was that I could be incorrectly allocating them.
CodePudding user response:
scanf %s
expects a pointer to space to which it can write a string.
arr[i].name
was never initialized. It's junk. It's not a (valid) pointer. You need to initialize arr[i].name
so that it points to space to which scanf
can write a string.