Search code examples
arrayscpointersmalloc

Arrays and pointers in C using malloc


I have this code which works. But I'm confused about how pointer arrays work, don't you have to initialize the array? How is this block of code able to just have &arr[i]. Secondly, why don't we need to dereference the pointer to manipulate the data stored in the location the pointer is pointing to (the array)?

int *arr = malloc(size(int)*size);
for(int i = 0; i < size; i++) {
    scanf(" %d", &arr[i]);
}

I would've thought that you needed to dereference a pointer in order to manipulate the data it points towards. So I thought this would work:

int *arr = malloc(size(int)*size);
for(int i = 0; i < size; i++) {
    scanf(" %d", &*arr[i]);
}

Also, when we're trying to access the array. Why doesn't have a * in front of array[i] work?

//sums value of elements in array
while (i < size ) {
    sum += *array[i];
    i++;
}

Solution

  • But I'm confused about how pointer arrays work, dont you have to initialise the array?

    Yes, malloc does not provide any initialization. Yes, this code does some initialization. It uses scanf to read values into all the elements in the allocated memory.

    How is this block of code able to just have '&arr[i]'.

    Scanf expects the address of the int variable where the converted input shall be stored. Using & gets the address of array alement i.

    Secondly, why don't we need to derefernce the pointer to manipulate the data stored in the location the pointer is pointing to (the array)?

    You do not want to manipulate the content. You want scanf to do that for you. Therefore you must provide the address.

    int *arr = malloc(size(int)*size);
    for(int i = 0; i < size; i++) {
        scanf(" %d", &arr[i]);
    }
    

    This code is likely illegal. What is size(int) supposed to mean? You need sizeof.

    I would've thought that you needed to derefrence a pointer in order to manipulate the data it points towards. So I thought this would work:

    See above. You don't want to manipulate the data here. &*arr[i] This does not make sense. & and * cancel each other out. It is the same as arr[i] which will cause a warning as you must provide an address-

    Also, when we're trying to access the array. Why doesn't have a * in front of array[i] work?

    //sums value of elements in array
    while (i < size ) {
        sum += *array[i];
        i++;
    }
    

    Your array does not hold pointers. It holds int values. No need to dereference an int value.

    You probably need to revisit your learning material regarding arrays and pointers.