void main()
{
int *p=20;
printf("%d\n",*p);
}
此代码编译成功,但出现分段错误,我使用的是 gcc 编译器。
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;
}
我想你在想
int *p=20;
将 20 的整数值写入指针 P,但事实并非如此。
您实际上是在将 poinetr 值初始化为地址 20。在 print 语句中,您正在取消引用它,您可能无权这样做。
试试下面的代码
void main()
{
int a=20
int *p=&a;
printf("%d\n",*p);
}
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.