相关疑难解决方法(0)

C:char指针和数组之间的差异

考虑:

char amessage[] = "now is the time";
char *pmessage = "now is the time";
Run Code Online (Sandbox Code Playgroud)

我从C编程语言第2版​​中读到,上述两个陈述没有做同样的事情.

我一直认为数组是一种操作指针来存储一些数据的便捷方式,但显然情况并非如此...... C中数组和指针之间的"非平凡"差异是什么?

c arrays pointers

135
推荐指数
5
解决办法
5万
查看次数

转换指针 - 运行时有什么区别?

请考虑以下小示例代码:

#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 …

c pointers casting

18
推荐指数
4
解决办法
2077
查看次数

取消引用这个指针给了我-46,但我不知道为什么

这是我运行的程序:

#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行为.

c pointers casting dereference

-3
推荐指数
2
解决办法
1243
查看次数

标签 统计

c ×3

pointers ×3

casting ×2

arrays ×1

dereference ×1