Constant in C (part.1)

Han sang yeob·2021년 2월 15일
0

Basic of C language

목록 보기
8/9

"Hello Tony"

When we want to print out the statement above, memory in our computer need to save that in somewhere. Let's go through the steps in order to save that statement in our memory.

  1. Find some location in memory to store the string of text.
  2. At that location in memory, storn an 'H'.
  3. Exactly after the 'H', at the very next byte, store an 'e'.
  4. Continue through this process until all characters of the string have been stored.
  5. Add a NULL byte (all zero) at the end.
    -The computer need one extra byte to store the string (which is space for NULL)

Now, let's look at this lines of code.

char *string;
string = "Hello Tony";

The variable 'string' is a pointer. Every pointer contains memory address. In another word, it is pointing to the address of where ths letter 'H' is stored in memory. What if we want to change this string of text into something else? Can we do it like,

char *string;
string = "Hello Tony";
string = "Hello Vy";

We can but what we are doing is just makinng string(pointer) to point different string of text("Hello Vy") which is stored somewhere else in the memory.We need to remember that string is just a pointer which can only mean memory address not actual strings of text.
So, when we write that code, what happens to

string = "Hello Tony";

??
It is still there. It is still sitting in memory excatly where it was. However, we have no way to find it now becuase we have changed where our pointer was pointing.

Consider this code,

char *string;
string = "Hello Tony";
string = "Hello Vy";
string = "Hello Tony";

We have pointer named string and we are pointing to a string of text("Hello Tony"). Then, we are setting the pointer to point to new string("Hello Vy").
The last line of code, did we now set the pointer to point our memory address of original "Hello Tony" or are we pointing to new string of text?
The answer is it depends on the compiler. The mordern compiler is smart so it will point to original string of text("Hello Tony") which is at the first line like

At some memory address : "Hello Tony"
At a different memory address : "Hello Vy"

this is it for current compiler that we use nowadays.

profile
Learning IT in Vietnam

0개의 댓글