using pointers as members of struct

i want to use pointers as member of struct..my prgram should read ISBN numbers of multiple books from file

#include<iostream>
#include<fstream>

using namespace std;

struct inventory{

char *isbn;

};

void read_inventory()
{

ifstream fin;
fin.open("file.txt");

int row = 2;
int col = 2;
inventory **s;

s = new inventory*[row];



for (int i = 0; i < row; i++)
{
s[i] = new inventory[col];
}


//s[0].isbn = "1253782-01-00";
//s[1].isbn = "1111223213124";


s[0][0].isbn= new char[20];
s[0][1].isbn = new char[20];

for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{

fin >> s[i][j].isbn;
}

}


for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{

cout<< s[i][j].isbn;
}

}

}


int main()
{

read_inventory();




}
I didn't run your code, but realize that you're only pointing s[0][0].isbn and s[0][1].isbn to valid char arrays. All of your other elements, s[0...row-1][0..col-1].isbn, are not pointing to valid data, so doing fin >> s[i][j].isbn at that point is invalid.
Ar12414 wrote:
i want to use pointers as member of struct


Why?
Your struct has one member only. A char pointer.

Do yourself a favour. Use C++. Use a string. Don't use char pointers. Don't use dynamic memory allocatino. Don't use arrays. Don't make a 2D array of char. JUST STOP AND WRITE C++ INSTEAD.
Your program has the following bugs and shortcomings. All of these would be fixed if you used the C++ facilities available to you such as strings and vectors.
- The program leaks like a colander. You leak the s array and all of the isbn's.
- If you fixed the leaks, you probably wouldn't be able to copy one inventory to another without creating another leak.
- You only read the first 2 characters of each isbn. What if there are more?
- You can only read 2 isbn's. Not 1, not 3, not 17. Just two.


Topic archived. No new replies allowed.