arrayscpointers

Segmentation Fault / Memory Access Violation when accessing array of array (doublepointer)


This is my code.

I'm allocating memory to a dynamic array and trying to print it with fn().

I won't be able to pass the array normally (like int *v) I can only pass it as int **v for specific reasons.

#include <stdio.h>
#include <stdlib.h>

void fn(int **v, int size) {
    for(int i = 0; i < size; i++)
        printf("%d @ %p\n", *v[i], &*v[i]);
}

int main() {
    int *v = (int*)malloc(sizeof(int) * 4);
    v[0] = 1;
    v[1] = 2;
    v[2] = 3;
    v[3] = 4;

    fn(&v, 4);
}

Solution

  • Rather than writing *v[i] which is equivalent to *(v[0]) you want to use (*v)[i].

    You also don't want to cast malloc and should check that it succeeded before trying to use that memory.

    The size parameter and your i variable in the loop should probably be of type size_t but I'm assuming you're force to respect the signature of fn.

    #include <stdio.h>
    #include <stdlib.h>
    
    void fn(int **v, int size) {
        for(int i = 0; i < size; i++)
            printf("%d @ %p\n", (*v)[i], &(*v)[i]);
    }
    
    int main() {
        int *v = malloc(sizeof(int) * 4);
        if (!v) {
            fprintf(stderr, "Memory allocation problem.\n";
            return 1;
        }
    
        v[0] = 1;
        v[1] = 2;
        v[2] = 3;
        v[3] = 4;
    
        fn(&v, 4);
    }