C memory allocation (malloc)

#include <stdio.h> #include <stdlib.h> int main() { int *p, n, i; printf("Enter the size of the array:"); scanf("%d", &n); p = (int *)malloc(n * sizeof(int)); for (i = 0; i < n; i++) { printf("\n Enter element %d:", i + 1); scanf("%d", &p[i]); } for (i = 0; i < n; i++) printf("\n %d", p[i]); return 0; } 

Why do we need to write & in scanf if this array is not needed? p is a pointer to all memory spaces, therefore &p[i] should indicate the address of the pointer, but not where we want to store the data correctly? Also, if we write *p[i] in printf , it gives an error, p is a pointer, so we have to relate to it and store the data in the reserved space in memory, but it does not work? Even if I compile the above program, since it stops working after entering 3 values ​​as input.

-2
source share
4 answers

The index operator [] also performs dereferencing. It performs indexing and dereferencing immediately. p[n] equivalent to *(p+n) , that is, it goes to an offset and plays it. Therefore, &p[n] equivalent to p+n .

+2
source

If the value of p[i]

 p[i] = *(p+i) 

Then the location should be

 &p[i] 

So, you need to indicate to which location you want to save this value, and it will be &p[i]

or (p+i)

 &p[i] = (p+i) 
+2
source

Why do we need to write in scanf, if it is an array, is it not necessary?

Arrays decay to the pointer of the first element. Usually the expression a , where a is an array, turns into &a[0] .

Also, if we write * p [i] in printf, it gives an error, p is a pointer, so we have to respect it and store the data in the reserved space in memory, but it does not work?

No, you are trying to apply the unary * operator to what is not a pointer type. An expression of the form E1[E2] equivalent to (*((E1)+(E2))) , therefore, if everything that is given with * is not a pointer type, then the syntax is invalid.

+1
source

You need to write &n to tell scanf where to put the data. & is an address operator; it returns the memory address in which the variable is stored.

&p[i] will indicate the address of the i th element of the array.

0
source

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


All Articles