<分区>
考虑:
char amessage[] = "now is the time";
char *pmessage = "now is the time";
我读自The C Programming Language , 2nd Edition 以上两个陈述不做同样的事情。
我一直认为数组是一种操作指针来存储一些数据的便捷方式,但事实显然并非如此……C 中数组和指针之间的“重要”区别是什么?
<分区>
考虑:
char amessage[] = "now is the time";
char *pmessage = "now is the time";
我读自The C Programming Language , 2nd Edition 以上两个陈述不做同样的事情。
我一直认为数组是一种操作指针来存储一些数据的便捷方式,但事实显然并非如此……C 中数组和指针之间的“重要”区别是什么?
最佳答案
这是一个假设的内存映射,显示了两个声明的结果:
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07
0x00008000: 'n' 'o' 'w' ' ' 'i' 's' ' ' 't'
0x00008008: 'h' 'e' ' ' 't' 'i' 'm' 'e' '\0'
...
amessage:
0x00500000: 'n' 'o' 'w' ' ' 'i' 's' ' ' 't'
0x00500008: 'h' 'e' ' ' 't' 'i' 'm' 'e' '\0'
pmessage:
0x00500010: 0x00 0x00 0x80 0x00
字符串文字“now is the time”作为 16 元素的 char 数组存储在内存地址 0x00008000 处。该内存可能不可写;最好假设它不是。您永远不应该尝试修改字符串文字的内容。
声明
char amessage[] = "now is the time";
在内存地址 0x00500000 分配一个 16 元素的 char 数组,并将字符串文字的内容复制到它。该内存是可写的;您可以根据自己的喜好更改消息的内容:
strcpy(amessage, "the time is now");
声明
char *pmessage = "now is the time";
在内存地址 0x00500010 分配一个指向 char 的指针,并将字符串文字的地址 复制到它。
由于 pmessage 指向字符串文字,因此不应将其用作需要修改字符串内容的函数的参数:
strcpy(amessage, pmessage); /* OKAY */
strcpy(pmessage, amessage); /* NOT OKAY */
strtok(amessage, " "); /* OKAY */
strtok(pmessage, " "); /* NOT OKAY */
scanf("%15s", amessage); /* OKAY */
scanf("%15s", pmessage); /* NOT OKAY */
等等。如果您将 pmessage 更改为指向一条消息:
pmessage = amessage;
然后它可以在任何可以使用消息的地方使用。
关于C:char指针和数组的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1335786/