c++ - 怎么输入指针的值?即输入指针所指区域的地址。
阿神
阿神 2017-04-17 13:00:41
0
4
894
#include <iostream>
using namespace std;
int main()
{
    int *i;
    i=(int*)malloc(sizeof(int));
    ...  
    //用cin或scanf输入i的值,即输入给定的地址
    ...
    return 0;
}

试过用cin>>iscanf("%d",&i)都不行,应该怎样写?

阿神
阿神

闭关修行中......

reply all(4)
阿神

scanf does not have a method for inputting pointer types, so input numbers and convert them into addresses. The test code and results are as follows (the hexadecimal representation of 8866 is 22A2):

include<stdio.h>

int main()
{

int *i;
int i_temp;
i=(int*)malloc(sizeof(int));
printf("i的地址为:%p\n",i);
printf("请输入i的地址:");
scanf("%d",&i_temp);
i=(int*)i_temp;
printf("赋值后i的地址为:%p\n",i);

return 0;
}

左手右手慢动作

Enter a number and then cast (

伊谢尔伦

The question is not clear enough.
Do you want to assign a value to i? If you do this, your malloc address will no longer be referenced, which will cause a memory leak. It is what we usually call wild pointers.

If you want the content entered by the user to be stored directly in this memory, then scanf("%d",i), because i is originally an address, there is no need for &i here.

If you want to apply for a memory at an address specified by the user, I can tell you that there is no such requirement. The addresses we use are all virtual addresses, allocated by the system, and not just any address can be used. But the C language is very flexible, and it does not restrict you from the language level. If you do not do this, the following possibilities may arise:
1. This memory will be protected by the operating system, and a memory error will be reported directly, causing the program to crash.
2. You don’t know where the memory has been changed. Anyway, the reading and writing are normal and the operation is correct. But this situation is more dangerous. This is a timer. You never know when this memory will be stepped on. It will be confusing, and there may be a chain reaction. The entire call stack will be trampled to pieces, and it will be impossible to locate. This is how large programs crash.

阿神

Can’t you just look through cin’s manual?

cin >> *i;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!