Home > Blockchain >  Should I use arrays or pointer if i want a user defined sizes
Should I use arrays or pointer if i want a user defined sizes

Time:02-28

My question is simple if I have to input a data in an array with size user defined in C should I use pointers to store them or arrays

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

int main(){
    int *arr, n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    arr=(int *)malloc(n*sizeof(int));
    printf("Enter number of elements:\n");
    for(i=0; i<n; i  )
        scanf("%d", &arr[i]);
}

Or

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

int main(){
    int n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter number of elements:\n");
    for(i=0; i<n; i  )
        scanf("%d", &arr[i]);
}

Personally I find it more comfortable to use pointers, but as C treats array and pointers differently I may face problems in the future.

CodePudding user response:

The provided snippets don't match in their semantics. The one using 'pointers' allocates memory on the heap using malloc the other one will allocate memory on the stack (using alloca under the hood).


Furthermore C does not treat pointers and arrays that differently:

    int a[10];
    a[2] = 69;

is semanticly identical to:

    int* a = alloca(10 * sizeof(int));
    *(a   2) = 69;

Besides the sizeof() operator and how they are sometimes treated when passing them as parameters they are pretty much interchangeable.

So there is no real difference you can choose what you prefer.


And because you don't seem to know the difference between stack and heap:

Allocating memory on the stack has the advantages of:

  • being faster
  • less memory management

but:

  • might overflow the stack when you allocate to much (~ 8kb)
  • will stay allocated and take up system ressources until function goes out of scope

PS: you should always use free() when using malloc() even in examples

CodePudding user response:

The other huge difference that has been hinted at but not totally explained is the life time of those 2 arrays.

If this was a function to read a file and return an array of ints from it

int* ReadInts(){..}

The malloc one

int*ReadInts(){
     int * result = malloc(....);
     ...
     return result;
}

works fine, but the vla one does not

int*ReadInts(){
     int result[X];
     ...
     return result;
}

your compiler might compile it (maybe with a warning) but this is bad code. result will be released when ReadInts returns, so this is Undefined Behavior

  • Related