What causes the reappointment of this integer pointer?

I am new to C and I have this question. why the following code failure occurs:

int *a = 10;
*a = 100;
+3
source share
10 answers

Because you are trying to write 100 to memory location 0x0000000A, which is probably not allocated to your program. I.e

int *a = 10;

does not mean that the pointer "a" points to a place in memory with a value of 10. This means that it points to address 10 (0x0000000A) in memory. Then you want to write something to this address, but you do not have β€œrights” to do this, since it does not stand out

You can try the following:

int *a = malloc(sizeof(int));
*a = 100;

, . int, . 32- 32 , int 32 , ( ) 8 , 4. .

+20

, (10).

int cell = 10;
int *a = &cell; // a points to address of cell
*a = 100;       // content of cell changed

, , C.

+12

malloc(), , int. :

a = malloc(sizeof(int));

, , . , ,

long *a;

( , 32- int long ). , , :

a = malloc(sizeof *a);

" , a", int, , , . , , - . - , , .

, (.. ) sizeof, , . sizeof , .

+7

- a. .

int *a = NULL;

a = malloc (sizeof (int));

if (a != NULL)
{
*a =10;
}

.

, .

.

int a* = NULL;
int b = 10;

a = &b;

, -

*a = 100;

, b == 100

: http://home.netcom.com/~tjensen/ptr/pointers.pdf

+2

,

int *a = 10;

a. a 10.

,

*a = 100;

100 , a.

:

  • , . ( 10)
  • , , , . , , - /. !
+2

int, 10 (), int . 10 , . :

int *a;
a = malloc(sizeof(int));
*a = 10;
printf("a=%i\n", *a);
free(a);
+1

? 10 int *, :

int *a = (int *) 10;
*a = 100;

100 10. , .

+1

, , , , - ( !).

0

, , . ?

(int*) a = 10;
(*a) = 100;

[10-13]. , - , - (, .data,.bss stack). , , .

C . . :

(void*) v = NULL;

. ? , 0.

:

struct Hello {
    int id;
    char* name;
};

...

struct Hello* hello_ptr = malloc(sizeof Hello);
hello_ptr->id = 5;
hello_ptr->name = "Cheery";

, malloc? Malloc . :

void* malloc(size_t size);

, , . , , , :

free(hello_ptr);

malloc, , , , -.

, , ? , "Cheery". . .

0.1.2.3.4.5. 6
C h e e r y \0
0

:

int* a = 10;
*a = 100;

. , . .

:

"Pointer-to-int 'a' becomes 10"
"Value-pointed-to-by 'a' becomes 100"

:

"Value-pointed-to-by 10 becomes 100"

... , 10 , .

:

int* ptr = (int*)10;  // You've guessed at a memory address, and probably got it wrong
int* ptr = malloc(sizeof(int)); // OS gives you a memory address at runtime  

, , . , ?

0

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


All Articles