Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allocating array and assigning values from a function C

C question

Hi,

I am passing a double pointer to a function to allocate a double array and initialise the array inside the function with lets say 10.10;

I do the following but get segmentation fault when I access the array in main;

void function(double **array, int size){

    *array = (double*) malloc(size * sizeof(double)); 
    int i;
    for(i=0;i<size;i++){
    *array[i] = 10.10;
    }


}

int main(){

    double *array = NULL;

    function(&array,20);
    printf("array[0] = %lg\n",array[0]);// here is where I get segmentation fault


}

Any help ?

like image 482
Bibrak Avatar asked Oct 28 '25 01:10

Bibrak


2 Answers

You have fallen foul of operator precedence.

Change:

for(i=0;i<size;i++){
    *array[i] = 10.10;
}

to:

for(i=0;i<size;i++){
    (*array)[i] = 10.10;
}

Note that if you had compiled with warnings enabled (e.g. gcc -Wall ...) your compiler would have caught this for you. Always compile with warnings enabled and always pay heed to, understand and fix any warnings.

like image 129
Paul R Avatar answered Oct 30 '25 18:10

Paul R


*array[i]

doesn't mean what you think it does (look it up using a C operator precedence table).

Instead of unreadable, ugly and confusing (yes, it just confused you) code, use a temporary variable (and do not for the love of God cast the return value of malloc!):

void function(double **array, int size)
{
    if (array == NULL) return;

    double *tmp = malloc(size * sizeof(*tmp)); 
    if (tmp == NULL) {
        *array = NULL;
        return;
    }

    int i;
    for (i = 0; i < size; i++) {
        tmp[i] = 10.10;
    }

    *array = tmp;
}

Also, return 0; from main(). Really.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!