Trying to understand * and & in C ++

I have a few questions. This is not homework. I just want to understand better.

So, if I have

int * b = &k;

  • Then it kshould be an integer, but it bis a pointer to a position kin memory, right?

  • What is the main "data type" b? When I output it, it returns things like 0x22fe4c, which I assume is hexadecimal for the memory position 2293324, right?

  • Where exactly is the memory position "2293324"? "Heap"? How can I display the values of, for example, in memory positions 0, 1, 2and so on?

  • If I deduce *b, this is the same as the output kdirectly, because it *somehow means the value that it points to b. But it looks different than the announcement bthat was announced int * b = k, so if it *means “value”, then it doesn’t mean “declare bvalue k? It’s not, but I still want to understand what it means, the language is wise.

  • If I post &b, it actually returns the address of the pointer itself and has nothing to do with k, right?

  • I can also do int & a = k;that that seems to match int a = k;. As a rule, there is no need to use &this way?

+4
4

1- .

2 " ". int. . "int" "char" c/++.

3 , . . b-- ( "b" "int" . , , int.)

4- * . . =. , == , =. .

5- & b - b. k, b k. , (** (& b)), , , b. k. , .

6- int & a = k a k. a , , k. a = 1, k 1. .

, . .

+1

:

  • , b - pointer k: k , k.

  • " " b - int: , , , b int, b: b - .

  • : , , , , .

  • * de-reference b. , b - , *b - , at b. k, *b k.

  • , &b - , k b.

  • int & a = k k, , k. , , , .

:

void addThree(int& a) {
   a += 3;
}

int main() {
    int a = 3; //'a' has a value of 3
    addThree(a); //adds three to 'a'
    a += 2; //'a' now has a value of 8

    return 0;
}

addThree a, , int a main() .

:

void addThree(int* a) { //Takes a pointer to an integer
   *a += 3; //Adds 3 to the int found at the pointer address
}

int main() {
    int a = 3; //'a' has a value of 3
    addThree(&a); //Passes the address of 'a' to the addThree function
    a += 2; //'a' now has a value of 8

    return 0;
}

, :

void addThree(int a) {
   a += 3; //A new variable 'a' now a has value of 6.
}

int main() {
    int a = 3; //'a' has a value of 3
    addThree(a); //'a' still has a value of 3: The function won't change it
    a += 2; //a now has a value of 5

    return 0;
}
+2

. * . & (lvalue) . . , . , .

+1

3 - k - , . k - , . , b. , , malloc(), calloc(),.... , alloca() ( _alloca()) (alloca() ).

An example with an array:

int array_of_5_integers[5];
int *ptr_to_int;
int (*ptr_to_array_of_5_integers)[5];

    ptr_to_int = array_of_5_integers;
    ptr_to_array_of_5_integers = &array_of_5_integers;
+1
source

Source: https://habr.com/ru/post/1621741/


All Articles