i have to program a function which asks for an array and its size, and then prints its values. The main function must call 2 other functions, both of them take two arguments (an array and its size). The first one asks for values to fill the array, the second one prints each value.
Im new to C and to programming in general, so any tips and useful info is very welcomed. I know very little about pointers aswell.
void requestarray(int a[], int size){
int i;
for (i=0;i<size;i++)
{
printf("Insert value for %d position of the array\n",i);
scanf("%d\n",&a[i]);
}
}
void printarray(int a[], int size){
int i;
for (i=0;i<size;i++){
printf("%d\n",a[i]);
}
}
int main(void){
int size;
printf("Insert array length\n");
scanf("%d\n",&size);
int a[size];
requestarray(&a[size],size);
printf("\n");
printf("The array is\n");
printarray(&a[size],size);
return 0;
}
the program compiles but does not work. when i debug it using gdb, i place a breakpoint after
int a[size];
then i print the value of a and it returns an array with size length and random values (mainly big numbers). Then i place a breakpoint after
requestarray(&a[size],size);
(which should modify the values of the array) but it returns the same values as printed in the previous breakpoint.
if i change the code in the main function like this
requestarray(a[size],size);
printf("\n");
printf("The array is\n");
printarray(a[size],size);
the debugger gives me this warning
arreglo1.c: In function ‘main’:
arreglo1.c:33:14: warning: passing argument 1 of ‘requestarray’ makes pointer from integer without a cast [-Wint-conversion]
resquestarray(a[size],size);
^
arreglo1.c:8:6: note: expected ‘int *’ but argument is of type ‘int’
void requestarray(int a[], int size){
^~~~~~~~~~~~
arreglo1.c:36:16: warning: passing argument 1 of ‘imprimearreglo’ makes pointer from integer without a cast [-Wint-conversion]
printarray(a[size],size);
^
arreglo1.c:17:6: note: expected ‘int *’ but argument is of type ‘int’
void printarray(int a[], int size){
^~~~~~~~~~~~
aas the parameter. BTW, the error message you quoted in the title doesn't come from that code. See minimal reproducible example.'\n'inscanf ("%d\n", &a[i]);is wrong, simplyscanf ("%d", &a[i]);will do. (all conversion specifiers other than"%c"and"[...]"consume leading whitespace) Alsorequestarray (a, size);is all that is needed. Andvoid requestarray(int *a, int size)would shown an understanding of the array/pointer conversion that takes place.scanf()and trailing white space in a format string — it is the epitome of appalling UI/UX to make people predict what they'll need to enter next before they can finish entering what is currently expected.