Re: char* array confusion
This is because of your line:
structArray[ i ].name = temp;
You are merely setting structArray[ i ].name to hold the address of the string. Since you only have one address (temp is only allocated once) all four enties in structArray will hold the same pointer and therefore point at the same string - being the last that you set. To fix it do the following:
for (int i=0; i<4; i++)
{
structArray[ i ].name = new char[4];
itoa(i, structArray[ i ].name, 10);
cout << structArray[ i ].name << endl;
}
You should also bear in mind that an integer could be up to ten characters long so you should allocate 11 bytes for the name (obviously unless you know the value will never be this big).
An alternative would be to adjust the definition of your struct to be:
struct test
{
char name[4];
}
This way you don't need to worry about pointers.
An even better way would be to use std::string.
I hope this helps and doesn't just confuse you even further,
Oliver
Re: char* array confusion
Hi,
The following code is something better:
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void main(int argc, char* argv[])
{
struct test
{
char* name;
};
test * structArray = new test[4];
char *temp = new char[4];
for ( int i = 0; i< 4; i++)
{
itoa(i,temp,10);
structArray[i].name = new char[strlen(temp)+1];
strcpy(structArray[i].name,temp);
cout<< structArray[i].name ;
}
cout<< structArray[0].name ;
cout<< structArray[1].name ;
cout<< structArray[2].name ;
cout<< structArray[3].name ;
}
Re: char* array confusion
Hi,
I am sory i must [blank i blank]write
The following code is something better:
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void main(int argc, char* argv[])
{
struct test
{
char* name;
};
test * structArray = new test[4];
char *temp = new char[4];
for ( int i = 0; i< 4; i++)
{
itoa(i,temp,10);
structArray[ i ].name = new char[strlen(temp)+1];
strcpy(structArray[ i ].name,temp);
cout<< structArray[ i ].name ;
}
cout<< structArray[0].name ;
cout<< structArray[1].name ;
cout<< structArray[2].name ;
cout<< structArray[3].name ;
}
Re: char* array confusion
closer but you are only allocating 4 bytes for temp then using as many as 10 bytes in itoa. Of course in your example it won't be a problem as i runs from 0 to 3.
As the maximum length of an integer is 10 digits, you need a buffer of 11 to cover all options.
You are also creating a lot of memory on the heap that (1) you could create locally and (2) you are not deleting later.
Preferably also you should learn to use the Standard Libraries.
Do not use <iostream.h> but <iostream>.
Also rather than itoa (which is not standard) you can use either printf (which at least is) or even more preferably use strstream. With strstream you don't need to worry about allocation.
The best things come to those who rate