[英]Pointer array and structure in C
I am nowhere lose to even guessing how come we get the given output .我什至不知道我们是如何得到给定输出的。 Can I please get some explanation?
我能得到一些解释吗? Also, any short and quick resources to try similar questions?
另外,是否有任何简短而快速的资源来尝试类似的问题?
void main()
{
struct a
{
char ch[10];
char *str;
};
struct a s1={"Hyderabad","Bangalore"};
printf("\n%c%c",s1.ch[0],*s1.str);
printf("\n%s%s",s1.ch,s1.str);
getch();
}
Ans: HB, HyderabadBangalore Ans: HB, 海得拉巴班加罗尔
struct a s1={"Hyderabad","Bangalore"};
assigns "Hyderabad" to ch
and "Bangalore" to str
.将 "Hyderabad" 分配给
ch
,将 "Bangalore" 分配给str
。
printf("\\n%c%c",s1.ch[0],*s1.str);
prints the first character of the strings.打印字符串的第一个字符。 Since
ch
is an array, ch[0]
represents its first character.由于
ch
是一个数组,因此ch[0]
表示它的第一个字符。 Since str
is a character pointer, it points to the first character of a string here.由于
str
是一个字符指针,所以它在这里指向一个字符串的第一个字符。 So, *s1.str
will have value 'B'因此,
*s1.str
将具有值 'B'
printf("\\n%s%s",s1.ch,s1.str);
simply prints all characters of both strings.简单地打印两个字符串的所有字符。 Fundamentally,
ch
is equal to &ch[0]
, the address of the first character in the array.从根本上说,
ch
等于&ch[0]
,即数组中第一个字符的地址。 And, str is pointer variable which holds the address of first character of the string literal "Bangalore".而且, str 是指针变量,它保存字符串文字“Bangalore”的第一个字符的地址。
%c
is only for single character. %c
仅用于单个字符。 Example H.示例 H。
$s
is for string. $s
用于字符串。 Example Hyderabad.示例海得拉巴。
s1.ch[0]
points to first character of String ch ->H s1.ch[0]
指向字符串 ch ->H 的第一个字符*s1.str
is a pointer. *s1.str
是一个指针。 It points to the value stored at address of str.它指向存储在 str 地址处的值。 It will be ->B
它将是 ->B
Hence you get HB
因此你得到
HB
\\n
means a new line (as in java). \\n
表示换行(如在 java 中)。
Here is your output according to requested question这是根据要求的问题您的输出
void main()
{
struct a
{
char ch[10];
char *str;
};
struct a s1={"Hyderabad","Bangalore"};
printf("%c%c",s1.ch[0],*s1.Str[0]);
printf("\t%s%s",s1.ch,s1.str);
getch();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.