B
bowlderyu
Hello, all.
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c
#include <stdio.h>
#define LEN 20
struct info {
char first[LEN];
char last[LEN];
int age;
};
struct pinfo {
char * first;
char * last;
int age;
};
int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}
//end test1.c
It can work.I know a little,but not very detail that the second struct pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Thank you.
bowderyu
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c
#include <stdio.h>
#define LEN 20
struct info {
char first[LEN];
char last[LEN];
int age;
};
struct pinfo {
char * first;
char * last;
int age;
};
int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}
//end test1.c
It can work.I know a little,but not very detail that the second struct pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Thank you.
bowderyu