Understanding Pointers and Indirect Operators

Asked 2 years ago, Updated 2 years ago, 142 views

I don't know why the code below is valid for char str [100] = "Hello"; not char*str = "Hello";I understand that I can only put an address in the pointer, but is that not true?

Also, does this mean that "Hello" is recognized by the computer as an array (string) first, pointing to the first address of the string, so the pointer has an address and char*str="Hello"; is established?

#include<stdio.h>

int main(void){
    char*str="Hello";

    printf("%s\n", str);

    return 0;
}

c++ c pointer

2022-09-30 21:47

3 Answers

I think it's good to understand that "Hello" is recognized by the computer as an array (string) first, pointing to the first address of the string, so the pointer has an address and char*str="Hello"; is established.

When the program in question is compiled, the compiler recognizes that "Hello" is a string (character constant).

When the object code (a program compiled in C language) is loaded, the memory reserves the space to store the constant "Hello" and variable Str, a pointer to the string, and initializes ("Hello" has a 6-byte string copied from the object code and str is set to Null."

Then, when *str="Hello"; is executed, the str will have the address "Hello" (pointer to "Hello") in it.


2022-09-30 21:47

"Hello" is called a string literal by the C language specification and
The type is const char*.
The str type is char*, so it is a pointer.
This means replacing the pointer with the pointer.


of the string "Hello" reserved on the stack when this line is executed The first address will be replaced by str.


2022-09-30 21:47

char*str="Hello"; declares the pointer variable str, and its initial value is the address of the area where "Hello" is located.

The question says "indirect operator", but I understand that the * used in the declaration statement is not an "indirect operator".The 子indirect operator 」 is the operator used in the execution statement to indicate the contents of the area indicated by the address by placing it before the address.

I don't know what the * used in the declaration statement is called, but it means that the variables that follow, the array is a pointer variable, and the pointer array.


2022-09-30 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.