简体   繁体   中英

change pointer of char[] in c++

I had to write a program that declares char text[16]; and int number; and then fills it with input from the user. Then I have to call another function (without passing anything) and recall that data from the stack and display it. I was able to find both of them

// This is the function that is called without passing any variables
int   number; 
char  text[16];

cout << *(&text + 5) << endl; // This outputs the correct text but I can not figure out how to assign it to text
number = *(int*)(&number + 20); // This works and outputs the correct number and saves correctly to int number;


cout << "\tnumber: "
  << number
  << endl;
cout << "\ttext:   "
  << text
  << endl;

I would like to know if there is a way to transfer the text from *(&text + 5) to char text[16];

What you are doing is going to result in undefined behavior. Depending heavily on the compiler and therefore in turn on the architecture. The proof being that when I compile and run your code with different optimization flags I get different results. Check out https://en.wikipedia.org/wiki/Buffer_overflow

The first expression *(&text + 5) evaluates to taking the address of the text pointer in memory, adding 5 to it and then dereferencing that to get a character value that is stored at that location. This can be pretty much anything on the stack at that time.

&number + 20 will definitely go off the "visible" stack, this is pointer arithmetic and will result in you adding 20*sizeof(int) to the pointer to the memory address of number on the stack.

If this is what you are intending to do then you should probably use strcpy as suggested by @JafferWilson

From reading the comments on the answer by Curious the answer is:

There is no proper way to read local variables in another function in C++ without passing them (or pointers to them or references to them) as parameters (or within objects you pass as parameters).

You can assign file scope (so called global) variables and read them in other functions. That is almost always a bad idea.

I get the feeling you might be coming from an assembler programming background to even try this sort of thing. You need to surrender a bit more to the structured programming paradigm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM