I wrote this simple code to test a bigger implementation I have and I get trash values plus a seg fault. One solution is to declare int* a and int* b as global and take out the arguments of fill. My question is, what is the consideration of memory handling in both cases, and why does it throw an error?
#include <stdio.h>
#include<stdlib.h>
#define LENGTH 4
void fill(int* a, int* b){
a = (int*) malloc(LENGTH * sizeof(int));
b = (int*) malloc(LENGTH * sizeof(int));
for(int i=0; i< LENGTH;i++){
a[i]=i;
b[i]=i+10;
}
}
void printArray(int* a, int* b){
for(int i = 0 ; i < LENGTH; i++)
printf("%d\n",a[i] );
for(int i = 0 ; i < LENGTH; i++)
printf("%d\n",b[i] );
}
int main(){
int* a;
int* b;
fill(a,b);
printArray(a,b);
}