考虑:
char amessage[] = "now is the time";
char *pmessage = "now is the time";
Run Code Online (Sandbox Code Playgroud)
我从C编程语言第2版中读到,上述两个陈述没有做同样的事情.
我一直认为数组是一种操作指针来存储一些数据的便捷方式,但显然情况并非如此...... C中数组和指针之间的"非平凡"差异是什么?
请考虑以下小示例代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *i;
char *c1, *c2;
i = malloc(4);
*i = 65535;
c1 = i;
c2 = (char *)i;
printf("%p %p %p\n", i, c1, c2);
printf("%d %d", *c1, *c2);
free(i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我分配内存来存储一个指向的整数i.然后,我存储值65535(1111 1111 1111 1111)*i.我接下来要做的是让两个char*指针也指向整数.我做了两次,但是用两种不同的方式:c1 = i;和c2 = (char *)i;.最后,我在屏幕上打印所有指针和所有值.这三个指针指向同一个地址,这两个值*c1和*c2正确(-1) .
但是,编译器会在此行中生成警告:c1 = i;.生成警告是因为我没有使用(char *)强制转换进行分配.
我想问的是为什么编译器会生成此警告,因为我没有看到使用中的任何差异c1 = i …
这是我运行的程序:
#include <stdio.h>
int main(void)
{
int y = 1234;
char *p = &y;
int *j = &y;
printf("%d %d\n", *p, *j);
}
Run Code Online (Sandbox Code Playgroud)
我对输出有点困惑.我所看到的是:
-46 1234
Run Code Online (Sandbox Code Playgroud)
我把这个程序写成了一个实验,不知道它会输出什么.我期待可能有一个字节y.
这里发生了什么"幕后"?解除引用如何p给我-46?
正如其他人指出的那样,我必须进行明确的施法才能导致UB.我没有改变这一行char *p = &y;,char *p = (char *)&y;所以我没有使下面的答案无效.
此程序不会导致此处指出的任何UB行为.