Maybe I've been up too long today, but I can't figure out why this is working:
int main() {
struct emf_struct {
long num;
char *str;
double real;
};
struct emf_struct emf [10];
emf[1].real= 4.5;
emf[1].str = "This is a string";
emf[1].num = 1234567890;
printf("%d-%s-%f\n", emf[1].num, emf[1].str, emf[1].real);
return(0);
}
When compiled under Microsoft (just cl filename), the output is:
1234567890-This is a string-4.500000
I could understand it if the struct had used a character array, e.g., char str[32], but this is a pointer to a string and it's a simple assignment of a literal (that has no address) to that pointer.
- Where did the memory space for the assignment come from? Shouldn't I have had to malloc?
- Without it, shouldn't the assignment have overwritten the real variable coming after str in the struct? (Packing seemed to have no effect.)
Thanks!
EDIT: C is not my primary programming language. The comments and replies people have provided have helped me realize something: literals have "addresses" maintained by the compiler, something I knew was true for initialization but not for assignments. I thought one needed to do this:
int main() {
char *foo;
foo = (char *) malloc(17);
strcpy(foo, "This is a string");
printf("%s\n", foo);
return(0);
}
when in fact all I need do is this:
int main() {
char *foo;
foo = "This is a string";
printf("%s\n", foo);
return(0);
}