0

I am trying to understand how malloc and pointer works.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *p;
    int b = 15;
    p = (int *)malloc(sizeof(int) * 10);
    for (int i = 0; i < 5; i++) {
        p + i = &b;
    }
}

The above code gives error expression is not assignable p + i = &b;

As far as I understand, malloc gives the starting address of the memory allocated in heap which I typecast to hold the address of integers. So technically, p + i should be able to hold any integer address, but the code throws an error. Can you please explain why this is wrong.

Thanks

Naveen Ramanathan
  • 2,166
  • 1
  • 19
  • 21
  • 4
    Do you mean `*(p + i)`? (Or perhaps `p[i]`?) – Oliver Charlesworth Apr 24 '16 at 19:15
  • 2
    Major confusion here, Firstly, `p + i` is an expression, which cannot be an **l-value**. Secondly, the memory pointed by `p + i` can hold integer, which can be done using `*(p + i)`, but you are trying to make it hold `int *`. – Haris Apr 24 '16 at 19:16
  • Correct me if I am wrong. int b = 25; int *a = &b; int c = 50; a = &c. When the above code works, why doesn't the one allocated by malloc in the question doesn't work. The memory pointed by p + i can hold integer. Then why can't I change p + i to point to the address of an integer. – Naveen Ramanathan Apr 24 '16 at 19:18
  • 1
    Please don't cast the return of `malloc` https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Gustedt Apr 24 '16 at 19:59

2 Answers2

0

The line of code p = (int *)malloc(sizeof(int) * 10); means that the pointer p is assigned the address of the first element of the dynamically allocated array with malloc(),which has allocated an int array consisting of 10 elements.

If you want to assign 5 of these elements the value of b then you write:

for (int i = 0; i < 5; i++) {
    p[i] = b;
}

If however you want an array of 10 integer pointers and want to assign 5 of them the address of b,then you write:

int **pointer = (int **)malloc(sizeof(int *) * 10);
for (int i = 0; i < 5; i++) {
    pointer[i] = &b;
}

Don't forget to free dynamically allocated memory when you finish.

machine_1
  • 4,266
  • 2
  • 21
  • 42
0

p + i is pointing to an address on your memory, the same as &(p[i]). You can't change the address of the memory, so that's why the compiler is saying the expression is not assignable.

If you want to save an int on that address you need to use *(p+i) = b.

But if you want to save the address of an int you need an array which holds int*, so you need to declare p as an int** and allocate its memory with the sizeof(int*). That way your code would look like this:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int **p;
    int b = 15;
    p = (int**)malloc(sizeof(int*) * 10);
    for (int i = 0; i < 5; i++) {
        *(p + i) = &b;
    }
}
Gabriel Cangussu
  • 434
  • 5
  • 10