[英]Assigning string to char* in structure
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: 在Microsoft(只是cl文件名)下编译时,输出为:
1234567890-This is a string-4.500000 1234567890 - 这是一个字符串-450000
I could understand it if the struct had used a character array, eg, 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. 如果结构使用了字符数组,我可以理解它,例如char str [32],但这是一个指向字符串的指针,它是一个简单的文字(没有地址)到该指针的赋值。
Thanks! 谢谢!
EDIT: C is not my primary programming language. 编辑:C不是我的主要编程语言。 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);
}
Where did the memory space for the assignment come from?
作业的记忆空间来自哪里? Shouldn't I have had to malloc?
我不应该不得不使用malloc吗?
The string literal you are assigning allready resides in memory. 您分配的字符串文字已驻留在内存中。 With
同
char *foo = "bar";
you just have foo
point to that location. 你只有
foo
指向那个位置。 The pointer should really be char const*
though since string literals are immutable. 指针应该是
char const*
因为字符串文字是不可变的。
Why wouldn't it have to look like,
emf[1].str = &"This is a string";
为什么它看起来不像,
emf[1].str = &"This is a string";
??
Because a string literal is an array of char
s that (like any array) decays to a pointer under most conditions. 因为字符串文字是一个
char
数组(在任何数组中)都会在大多数条件下衰减到指针。 Exceptions to array decaying into a pointer? 数组衰减为指针的例外情况?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.