Arzental
Arzental

Reputation: 103

Create and fill a dynamic array within function C

I need to scan n numbers and then fill an array with the following scanned n numbers. I have to use both n and array inputs in a function as well as to use dynamic memory.

void input(int* buff, int* n);

int main() {
    int* data = NULL;
    int n;
    input(data, &n);

    for (int i = 0; i < n; ++i) {
        printf("%d ", data[i]);
    }
    return 0;
}

void input(int* buff, int *n) {
    if (scanf("%d", n) == 1 && getchar() == '\n') {
        if (*n <= 0) {
            error = 1;
        }
    }

    if (error == 0) {
        buff = (int*)calloc(*n, sizeof(int));
        if (buff == NULL) {
            error = 1;
        }
    }


 if (error == 0) {
        int count = 0;
        int p;
        for (int i = 0; i < *n; i++) {
            if (1 == scanf("%d", &p)) {
                if (count < *n) {
                    *(buff + count) = p;
                    count++;
                }
            }
       }

for (int i = 0; i < *n; i++) {
    printf("%d, ", *(buff + i));
    }
}

I didn't insert all the logic of my program in the first for since it doesn't really mater. The last for prints proper elements however I have a warning about an empty pointer.

When I return to the main and trying to print I've got an error about read access prohibition. Where did I do wrong?

Upvotes: 0

Views: 257

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148950

If you only need to allocate one single dynamic array in your function you can just return a pointer to it:

int *input(int *buf, int *n);
...
    data = input(data, &n);
...
int *input(int* buff, int *n) {
    ...
    return buff;
}

Upvotes: 0

4386427
4386427

Reputation: 44274

data in main isn't changed when you change buff inside input. In other words - data will still be NULL when the input function returns.

It's just like the n... For n you correctly pass a pointer to n and you need to do exactly the same for data.

Like:

void input(int** buff, int *n) {
              ^^
           // Notice the two *, i.e. pointer-to-pointer
    ....
    *buff = calloc(....
    ....

and call it like

input(&data, &n);

Upvotes: 3

Related Questions