Have a problem accessing some elements of a structure in a right way after typecasting.
Here my code:
void get_description(struct shmstruct *ptr/*, int number*/) {
char buff[MESGSIZE];
struct shmData *dparse;
snprintf(buff, MESGSIZE, "%s", &ptr->msgdata[0]);
dparse = (struct shmData *) buff;
printf("Number: %s", dparse->number);
printf("Description: %s", dparse->description);
}
Problem now is, that I get the number, like 123, but also the description in the first
line ->
printf(“Number: %s”, dparse->number);
like: 123 description
How can I get only the number?
(P.S.
struct shmData{
char number[4];
char description[1020];
};
)
It sounds like the number is not nul-terminated. You have the
numberfield and then immediately following you have thedescriptionfield.printf()assumes that you are giving it a nul-terminated string, and it will keep going until it hits the terminating nul character. It looks like in your case, there isn’t a nul terminating thenumberfield, soprintf()just keeps going and gets thedescriptionalso.Can all four characters from
numberbe used for digits?If the numbers are only 3-digits or fewer, then you can put a terminating nul right into the
numberbuffer. If you might need to read a 4-digit number from there, you need to copy out the digits into a temp buffer of at least 5 chars, and then nul-terminate.strncpy()doesn’t guarantee to nul-terminate, which is unfortunate. So we should always put in a terminating nul character in the last position so that no matter what, it is nul-terminated. Note that sometimesstrncpy()will put a nul for us, but it does no harm to make sure one is there.