I have this code, I want the "sum" function (which I want to add the first and last position of the array) to be applied to a given array. How do I take the last position of the array?
#include <stdio.h>
#define CUBO(a) a*a*a
int suma (int a[]);
int main()
{
int size;
printf("cant ar: ");
scanf("%i",&size);
int ar[size];
for (int i=0; i<size; i++)
{
printf("valror %i: ",i+1);
scanf("%i",&ar[i]);
}
printf("la suma es %i",suma(ar[]));
return 0;
}
int suma(a[]){
int sum;
sum= a[0] + CUBO(a[size-2]);
return sum;
}
The compiler tells me that "size" is not declared in the function, in python it would be a[-1], but how do I do it in C so that it indicates the last position of the array?
Indeed, if we look at the function
suma
:We see that
size
it is not defined in that function.size
It's not a global variable either, so the error you get is legitimate.Notice that
size
it is declared... in the functionmain
:But this variable is proper to the function
main
.If you need to use
size
ensuma
, you just have to pass it as a parameter:A small additional detail, note that to pass the array to
suma
you simply have to indicate the name of the variablear
without the brackets . The square brackets should only be used when we want to access a specific position in the array.The last position of the array is
size - 1
and notsize - 2
as you have in the code.In any case, the standard only understands arrays as elements whose size is determined at compile time. That is, its size must be a constant.
In your case this is not true since it
size
is a variable. This is what is known as VLA or Variable Length Array and its use has several implications:size
. What happens if the user enters 0 or a negative value?As a replacement for VLAs I suggest you use dynamic memory: