简体   繁体   English

你能帮我理解这个程序吗?

[英]Can you help me understanding this program?

Can you help me out to understand why I'm getting this output. 您能帮我了解为什么我得到此输出。

#include<stdio.h>
#include<string.h>
void main() {
char a[] = "Hello World";
char *p;
p=a;
printf("%d%d%d%d",sizeof(a),sizeof(p),strlen(a),strlen(p));
}

output: 1281111 (My OS is of 64-bits) 输出:1281111(我的操作系统是64位)

Saying that the above code should have shown 1241111(output) if It is compiled and ran on a 32-bit system. 说如果上面的代码在32位系统上编译并运行,则上面的代码应该已经显示1241111(输出)。 Due to 64-bit It shows 1281111. 由于是64位,因此显示1281111。

In my First year, I saw this question and when I went to look for the output, I get 1281111. 在我的第一年,我看到了这个问题,当我去寻找输出时,我得到了1281111。

But surprisingly above code's output has two options:1)12121111 and 2)1221111.(University Question). 但令人惊讶的是,以上代码的输出具有两个选项:1)12121111和2)1221111。(大学问题)。

If you change the printf() statement to the following, it's easier to see what's going on: 如果将printf()语句更改为以下内容,则更容易了解发生了什么:

printf("%d\n%d\n%d\n%d\n",sizeof(a),sizeof(p),strlen(a),strlen(p));

On my system, this results in the output: 在我的系统上,这将导致输出:

12
8
11
11

In other words: 换一种说法:

  • The size of the array is 12 bytes. 数组的大小为12个字节。 (11 for the string, plus one for the \\0 character.) (该字符串为11,加\\0字符为一个。)
  • The size of the pointer is 8 bytes (because I'm using a computer with 64-bit memory addresses, as opposed to a 32-bit computer which would likely output 4 ). 指针的大小为8字节(因为我使用的是具有64位内存地址的计算机,而32位计算机可能会输出4 )。
  • When used as strings ( char* pointers), a and p are equivalent. 当用作字符串( char*指针)时, ap是等效的。 (because p points to a .) The length of the string Hello World is 11 (since strlen() doesn't include the \\0 byte at the end of the string). (因为p指向a 。)字符串Hello World的长度为11 (因为strlen()在字符串末尾不包含\\0字节)。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM