0
#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.

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@exsnake If you need to modify an int, then a pointer to int is enough. But here you need to modify a pointer to int, then you need to use a pointer to a pointer to int.
4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.