Reputation: 117
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct product{
string productName;
float price;
};
int main()
{
struct product *article;
int n=2; // n represent here the number of products
article= (product*) malloc(n * sizeof(product));
for(int i=0;i<n;i++)
{
cin >> article[i].productName; // <=> (article+i)->productName;
cin >> article[i].price;
}
for(int i=0;i<n;i++)
{
cout << article[i].productName <<"\t" << article[i].price << "\n";
}
return 0;
}
My question is why this is wrong, because when I try to run this I get a segmentation fault. I used the GDB debugger to see which line is causing the problem, and this is the line that was causing this:
cin >> article[i].productName;
Why? This was bothering me for days...
Upvotes: 0
Views: 1290
Reputation:
Instead of malloc-ing object, use new
product *article = new product[n];
Upvotes: 0
Reputation: 31
Try using this:
#include <iostream>
#include <string>
using namespace std;
struct product{
string productName;
float price;
};
int main()
{
int n = 2; // n represent here the number of products
product *article = new product[n];
for (int i = 0; i<n; i++)
{
cin >> article[i].productName; // <=> (article+i)->productName;
cin >> article[i].price;
}
for (int i = 0; i<n; i++)
{
cout << article[i].productName << "\t" << article[i].price << "\n";
}
return 0;
}
article[0] was not initialized when you used cin
. If you use new[]
instead, it should work.
Upvotes: 1
Reputation: 560
When you allocate memory with the new
operator, it does two things:
In your case (malloc
), you do only the first part so your structure members are uninitialized.
Upvotes: 6
Reputation: 31675
article[0]
is not initialized (i.e. the constructor of struct product
has not been called for article[0]
). Therefore, article[0].productName
has not been initialized either.
Use new product[n]
instead of (product*) malloc(n * sizeof(product))
to initialize the array elements (and by transitivity the members of the elements).
Upvotes: 1