我正在研究结构,并且遇到了一些误解。我写了几个例子:
#include <stdio.h>
struct test{
char field[16];
};
int main(int argc, char * argv[]){
const char *string = "some string";
struct test t1 = {.field = *string};
struct test t2 = {.field = string};
struct test t3 = {.field = "some string"};
struct test t4 = {{'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0'}};
printf("t1::field = %s\n", t1.field); //prints s
printf("t2::field = %s\n", t2.field); //prints garbage character
printf("t3::field = %s\n", t3.field); //prints some string
printf("t4::field = %s\n", t4.field); //prints some string
}
输出:
t1::field = s
t2::field = 4
t3::field = some string
t4::field = some string
另一个例子是
#include <stdio.h>
struct test{
char field[16];
};
int main(void) {
const char *string = {'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0'};
struct test t = {.field = *string};
printf("t::field = %s\n", t.field); //segfault
}
输出为空。
这种行为对我来说还不是很清楚。分配数组内存时,我们可以将其第n个元素arr[n]
扩展为*(arr + n)
。因此,我希望我们char field[16]
使用some进行初始化char *
,将指针所指向的对象视为某个数组的第一个元素就足够了。
但是从行为来看,我的理解是完全错误的。您能对此做一个简短的解释吗?
struct test{ char field[16]; };
包含一个包含16个字符的字符数组 field
。数组可以初始化或复制到,但不能分配。
有效
struct test t1 = {.field = *string};
(初始化t1.field
为string[0]
(例如*(string + 0)
或*string
)
无效
struct test t2 = {.field = string};
(试图分配一个指针到字符串文字到阵列中,见C11标准- 6.3.2.1其它操作数-左值,数组和功能指示符(P3) )
有效
struct test t3 = {.field = "some string"};
(使用字符串文字初始化数组)
有效
struct test t4 = {{'s', 'o', 'm', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0'}};
(t4
与t3
使用括号括起来的初始化器相同,但省略了named-initializer ,该初始化.field
器指示从第一个成员开始进行成员填充,与之相同,请参阅C11标准§6.7.9初始化(p19))
您的“另一个示例”由于相同的原因而t2
失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句