Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to initialize a struct

Status
Not open for further replies.

cadbilbao

Programmer
Apr 9, 2001
233
ES
I declared:

struct Person
{
int ID;
char Name [50];
}
MyData[100];

The first time I call my program I fill 52 Data, but the
second time, I only fill 10. But the next 42 are still
filled (from the time before).

Is there any way to initialize MyData?

Regards.
 
Hello again.

I'm trying with:
memset((unsigned char*)&MyData, 0, sizeof MyData);

But, how is memory affected? Must I free memory after using MyData?

thank you very much
 
I'm not sure what you mean by "I fill 52 Data, but the
second time, I only fill 10. But the next 42 are still
filled". It looks like you're doing everything correctly, but as far as the physical memory is laid out, you have to make sure and take byte alignment into account. For instance, if you're using 8 byte alignment then each element of MyData[] will be 56 bytes (first multiple of 8). So, your examples will take up 5600 bytes of memory for the MyData array.

As for freeing the memory, you only need to free the memory if you allocate it (with a new or malloc(), etc.). If you're defining it on the stack, like in your example (MyData[100]) then you can't free it. If you try, you'll be freeing memory from another block of memory which you don't own and will cause unpredictable results.

Hope this helps.
 
well you can always do struct

Code:
Person                                              
{
    int            ID;
    char*             Name;
}
MyData[] = {
{1,"BOB"},
{2,"Steve"},
...
{100,"MIKE"}};

BUT this uses char pointers and I dont think it is the approach you are looking for.

The other approach is to do

struct Person                                              
{
int ID;
char name[50];
Person(int id,char* n):ID(id)
{
    strcpy(name,n,sizeof(n));
    name[strlen(n)]=0;
}
}
MyData[100];

Person* MyData[100];

for(int i = 0;i<100;i++)
{
    myData[i] = new Person(i,arrayOfNames[i]);
}

Matt






 
To fill all 100 structures with zeroes use

memset(MyData,0,(100 * sizeof(Person));

Note MyData when used without [] is already a pointer to the start of the 100 structure array in memory. You don't need to mess around with it. If ignorance is bliss then stupidity is an asset not a liability.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top