exsnake
exsnake

Reputation: 1823

dynamically sized array in C using a function

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

void dim(int*,int);
int main()
{
    int *array ;
    int n,i;
    scanf("%d",&n);
    dim(array,n);

    for(i=0;i<n;i++)
        scanf("%d",&array[i]);
    for(i=0;i<n;i++)
        printf("%2d",array[i]);
}

void dim(int *array,int n){
    array=malloc(n* sizeof(int));
}

why this don't work? i can't do this?

I can't give a dimension to an array through a function?

I tried to find on Internet how this works, but i dint find anything so i prefer to post it here for a direct answer.

Thanks! and sorry for my English.

Upvotes: 0

Views: 78

Answers (2)

Foggzie
Foggzie

Reputation: 9821

You're passing a pointer by value so dim isn't doing anything to it. You need to pass a pointer to a pointer into your function like so:

void dim(int **array, int n) {
    *array=malloc(n * sizeof(int));
}

then pass in your array like so:

dim(&array, n);

Upvotes: 4

Yu Hao
Yu Hao

Reputation: 122383

The array in the function is passed by value, what you allocated in dim doesn't affect the array in main, it's memory leak.

Instead, pass a pointer to pointer:

void dim(int **array,int n){
    *array=malloc(n* sizeof(int));
}

And call it like:

dim(&array,n);

Upvotes: 6

Related Questions