[英]How do I interpret the declaration char *x[5]?
My professor has a bit of code uploaded online, but I'm finding it hard to understand this variable: 我的教授有一些在线上传的代码,但是我发现很难理解这个变量:
char * x[5];
Does this represent 5 spaces x has for pointers to characters? 这是否代表x的5个空格来指向字符的指针? So if I were to say 所以如果我要说
x[0]="Apple";
would this be valid? 这会有效吗?
Does this represent 5 spaces x has for pointers to characters? 这是否代表x的5个空格来指向字符的指针?
Yes. 是。 One way to examine this is to evaluate sizeof(x)
, sizeof(x[0])
, and sizeof(*x[0])
. 一种检查方法是评估sizeof(x)
, sizeof(x[0])
和sizeof(*x[0])
。 On my x64 machine, those evaluate to 40, 8, and 1 -- pointers are 8 bytes long, so char* x[5]
declares five pointers. 在我的x64机器上,它们的值分别为40、8和1-指针的长度为8个字节,因此char* x[5]
声明了五个指针。
would
x[0]="Apple";
会x[0]="Apple";
be valid? 有效吗?
Yes, although it might not do what you expect. 是的,尽管它可能无法达到您的期望。 Here, x[0]
is being set to point to a string literal, and the values of x[1]
through x[4]
are undefined. 在此,将x[0]
设置为指向字符串文字,并且x[1]
至x[4]
的值未定义。 Note that because "Apple"
is a string literal, it's read-only; 请注意,由于"Apple"
是字符串文字,因此它是只读的。 you're not guaranteed to be able to modify it. 您不能保证能够对其进行修改。
Yes that what it is, ie an array of 5 char
pointers, and indeed 是的,它是什么,即5个char
指针的数组,实际上
x[0] = "Apple";
is valid. 已验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.