-2
void main()
{ 
    int *p=20;
    printf("%d\n",*p);
}

此代码编译成功,但出现分段错误,我使用的是 gcc 编译器。

4

3 回答 3

3

You defined p as a pointer to memory address 20. You are then trying to dereference that address when you use the *p syntax. Address 20 is unlikely to be in the range of memory you are allowed to access, so it will give you a segmentation fault.


char* i = "abcd"; tells the compiler to set aside space for the string in memory, and point i to that place in memory. You are still assigning the place in memory to the variable.

The *i in your printf means you want the value which is pointed to by i. In your comment, you won't actually get abcd, you will actually get a. This is because i points to the first character in the string "abcd", and that character is a.

If you want an example of how you can point to integers, take a look at this code:

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

int main() {
  int number = 5;           //A space in memory, set to the value 5
  int* pointer = &number;   //A pointer to point to the space in memory
  printf("%d\n", *pointer); //Using * to get the value pointed to by pointer
  return 0;
}
于 2012-08-08T08:26:49.800 回答
3

我想你在想

int *p=20;

将 20 的整数值写入指针 P,但事实并非如此。

您实际上是在将 poinetr 值初始化为地址 20。在 print 语句中,您正在取消引用它,您可能无权这样做。

试试下面的代码

void main()
    { 
        int a=20
        int *p=&a;
        printf("%d\n",*p);
    }
于 2012-08-08T08:40:02.620 回答
2

The pointer p points to the address 20 which is likely not yours. The printf call will try to print the contents of that memory, which is not allowed.

于 2012-08-08T08:27:09.170 回答