Ommik Ommik - 3 years ago 156
C Question

What is correct method assigning array in struct

I'm a total noob so this might be totally off but why

struct staff{
int id;
char lastdate[8];
char codeid[8];
};


in main I'm taking data from Mysql and:

...
while((row = mysql_fetch_row(confres)))
{
char *codeid = row[0];
char *maxdate = row[1];

info[i].id=i;
strcpy(info[i].codeid, codeid);
strcpy(info[i].lastdate, maxdate);

i++;
}
...


lastdate is in form YYYYMMDD and codeid a string.

When printing array out why is it 'lastdate's is ok but codeid which is string is just empty?

ID: 0
SHORT:
LAST DATE : 20170929

ID: 1
SHORT:
LAST DATE : 20170929
...

Answer Source

You need to make lastdate big enough to hold the 8 characters of the date plus the null terminator, so the structure should be:

struct staff{
    int id;
    char lastdate[9];
    char codeid[8];
};

You were writing outside the array, which results in undefined behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download