William Jones
William Jones

Reputation: 175

SegFault when accessing allocated array from different function

It has been a year since I've coded in C but I do not understand why this is segfaulting

// Assume all imports are made

int printAgain(double** array, int size) {

    int i = 0;
    while(i < size) {
        printf("Value: %f\n", *array[i]);
        ++i;
    }

    return 0;
}



int main(int argc, char *argv[]) {

    int size = 10;

    // Want an array of size 10 that contains doubles
    double *array = malloc(size * sizeof(double));

    if(array) {

        int i = 0;
        while(i < size) {

            // Doing irrelavent stuff here

            double value = 1.5; // 1.5 is random # I picked for this example
            array[i] = value;

            printf("Added to array: %f\n", array[i]);
            ++i;
        }

        printAgain(&array, size);

        free(array);
        return 0;
    }
}

The first print statement in main works fine, but in printAgain it will print the first element of the array but seg fault when trying to print the second element.

I believe I am allocating correctly, assigning the spots of the array to the values in the for loop then sending the address of the array to the printAgain function. In that function I de-reference the given address to access the array and print its' contents. I know seg fault occurs when accessing out of bounds/illegal memory space but I don't understand how that could be happening since I "believe" I correctly allocated and pass the address to the array from main.

I know I'm missing something extremely simple and rudimentary but I guess that is what 1 year of not coding in a language can do to you, so sorry about that.

Upvotes: 0

Views: 41

Answers (1)

ssd
ssd

Reputation: 2432

In main, array is already a pointer. You'd better pass it using printAgain(array, size); instead of printAgain(&array, size);. In connection, you need to change the function decoration from int printAgain(double **array, int size) to int printAgain(double *array, int size).

int printAgain(double *array, int size) {
    int i = 0;

    while (i < size) {
        printf("Value: %f\n", array[i]);
        ++i;
    }

    return 0;
}

int main(int argc, char *argv[]) {
    int size = 10;
    double *array = malloc(size * sizeof(double));

    if (array) {
        int i = 0;

        while (i < size) {
            double value = 1.5; // 1.5 is random # I picked for this example
            array[i] = value;
            printf("Added to array: %f\n", array[i]);
            ++i;
        }

        printAgain(array, size);

        free(array);
        return 0;
    }
}

Upvotes: 1

Related Questions