I am confused by how this C program is running. I am just trying to use a structure to store some variables and then be able to print them out in a separate function. Below is my code. What I don't understand is why is my first output includes both ip and key and not just ip.
#include <stdio.h>
struct device {
char ip[6];
char key[5];
};
void check(struct device cred);
int main ()
{
int i;
struct device cred[10];
strcpy(cred[0].ip, "192.16");
strcpy(cred[0].key, "45EA9");
check(cred[0]);
return 0;
}
void check(struct device cred)
{
printf("IP: %s\n", cred.ip);
printf("Key: %s\n", cred.key);
}
Output:
IP: 192.1645EA9
Key: 45EA9
ip
, it should bechar ip[7]
to hold the'\0'
-terminating byte. Same forkey
.printf
to know where to stop?N+1
elements to store anN
-character string. Since the terminator wasn't there,printf
just kept going and printed the contents ofkey
.strcpy()
operations, you'd probably get nothing printed for thecred.key
.