相关疑难解决方法(0)

是否可以将C指针初始化为NULL?

我一直在写类似的东西

char *x=NULL;
Run Code Online (Sandbox Code Playgroud)

假设是

 char *x=2;
Run Code Online (Sandbox Code Playgroud)

会创建一个char指向地址2 的指针.

但是,在GNU C编程教程中,它表示int *my_int_ptr = 2;将整数值存储2my_int_ptr分配时的任何随机地址.

这似乎意味着我自己char *x=NULL正在将NULL一个cast 的值分配给char内存中的某个随机地址.

#include <stdlib.h>
#include <stdio.h>

int main()
{
    char *x=NULL;

    if (x==NULL)
        printf("is NULL\n");

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

事实上,印刷品

一片空白

当我编译并运行它时,我担心我依赖于未定义的行为,或者至少是指定不足的行为,我应该写

char *x;
x=NULL;
Run Code Online (Sandbox Code Playgroud)

代替.

c pointers initialization

88
推荐指数
6
解决办法
3万
查看次数

C指针初始化和解除引用,这里有什么问题?

这应该是超级简单的,但我不确定为什么编译器在这里抱怨.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int *n = 5;

  printf ("n: %d", *n);

  exit(0);
}
Run Code Online (Sandbox Code Playgroud)

得到以下投诉:

foo.c:在函数'main'中:
foo.c:6:警告:初始化使得整数指针没有强制转换

我只想打印指针n引用的值.我在printf()语句中取消引用它,我得到一个分段错误.用gcc -o foo foo.c编译它.

c pointers dereference

1
推荐指数
1
解决办法
2392
查看次数

标签 统计

c ×2

pointers ×2

dereference ×1

initialization ×1