The difference between the expressions: int * a = 0; int * a = 10;

What's the difference between

int* a = 0;

and

int* a = 10;

?

+3
source share
5 answers

int* adeclares a variable aas a pointer to an integer.

=0and =10assign the variable a value.

Note that ais a pointer, its value must be an address.

  • An address 0has a special meaning: it NULL, represents a null pointer.

  • The address 10does not matter: it is a random memory address. Since this is not NULL, most functions will consider it as a valid address, dereference it, and thus create problems (undefined behavior) for your application.

+10
source

. !

int *a = 0;

. a int 0 NULL, , . , , , , NULL - .

int *a = 10;

. int, 10. -, , int 10 . , 10, , int - . a , a, NULL, , a, 10 - , , // .

+5
int* a = 0;

0 .

int* a = 10;

10 . (.. , ), !

, NULL.

+4

-, , .

int* a = 0;

, . , .

int* a = 10;

, , , , 10. , undefined .

+4

Here we assign a value to the pointer, int * a = 0; means int a * = NULL; However, in C ++, int * a = 10 does not compile because "Converting from an integer type to a pointer type requires reinterpret_cast, casting in C style or function style" because the compiler considers 10 to be an integral type and not pointer.

+1
source

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


All Articles