我对这个程序感到困惑.
#include <stdio.h>
int main(void)
{
int value = 10;
char ch = 'A';
int* ptrValue = &value;
char* ptrCh = &ch;
int* ptrValue1 = value;
char* ptrCh1 = ch;
printf("Value of ptrValue = %d and value of ptrValue1 = %d\n", *ptrValue, ptrValue1);
printf("Value of ptrCh = %c and value of ptrCh1 = %c\n", *ptrCh, *ptrCh1);
}
Run Code Online (Sandbox Code Playgroud)
编译这个程序时我收到两个警告
unipro @ ubuguest:/ SoftDev/ADSD/Module 1/Unit 1/Rd/C/System $ cc charPointers.c -o charPointers
charPointers.c:在函数'main'中:
charPointers.c:11:警告:初始化使指针来自没有
强制转换的整数charPointers.c:12:警告:初始化使得整数指针没有强制转换
我知道他们的意思.
在运行程序时,我收到以下错误.
unipro @ ubuguest:/ SoftDev/ADSD/Module 1/Unit 1/Rd/C/System $ ./charPointers
ptrValue = 10的值和ptrValue1的值= 10
分段错误
我知道我在第二个printf方法得到了错误.
所以我的问题是如果我在指针中存储一个值,为什么我们不能去引用它呢?它的行为是否像变量?
谢谢.
随着任务
char* ptrCh1 = ch;
Run Code Online (Sandbox Code Playgroud)
您将地址设置为0x41,而不是值.程序稍后将尝试取消引用0x41(即,在地址0x41处获取数据),这是一个非法地址.因此,分段错误