定义一个int类型的变量a的值为100,int类型的一级指针为p,指向a的内存地址通过指针p打印出a的值,通过指针p修改a的值为200
#include <iostream>
using namespace std;
int main() {
int a = 100;
int *p = &a; // 定义指针p并将其指向变量a的内存地址
cout << "a的值为:" << a << endl; // 通过变量名直接打印a的值
cout << "通过指针p打印a的值:" << *p << endl; // 通过指针p打印a的值
*p = 200; // 通过指针p修改a的值为200
cout << "修改后,a的值为:" << a << endl; // 通过变量名直接打印修改后的a的值
cout << "通过指针p打印修改后的a的值:" << *p << endl; // 通过指针p打印修改后的a的值
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:int main()
{
int *a = NULL;
a = (int *)malloc(sizeof(int));//为a分配内存
/*assert(a != NULL);*/
//将a的值赋为1
*a = 1;//将值赋给a内容,不直接赋值是因为a是指针变量不是变量,用a代表的是它所指的内容
printf("a=%d\n", *a);//打印a内容的值
free(a);//释放a的内存
a = NULL;//再将a的值赋为空指针
printf("a=%p\n", a);//打印a内容的值
return 0;
}