Reputation: 5462
here's a simple and short code I've been trying to run:
#include <stdio.h>
int const SIZE = 5;
void a(int *arr);
int main(){
int arr[5] = {1,2,3,4,5};
a(arr);
return 0;
}
void a(int *arr){
int *i;
for (i=arr; i<&a[5]; i++)
printf("%d",*arr[i]);
}
and i get the following errors/warnings:
main.c: In function ‘main’:
main.c:15: error: variable-sized object may not be initialized
main.c:15: warning: excess elements in array initializer
main.c:15: warning: (near initialization for ‘arr’)
main.c:15: warning: excess elements in array initializer
main.c:15: warning: (near initialization for ‘arr’)
main.c:15: warning: excess elements in array initializer
main.c:15: warning: (near initialization for ‘arr’)
main.c:15: warning: excess elements in array initializer
main.c:15: warning: (near initialization for ‘arr’)
main.c:15: warning: excess elements in array initializer
main.c:15: warning: (near initialization for ‘arr’)
main.c: In function ‘a’:
main.c:22: error: subscripted value is neither array nor pointer
main.c:23: error: array subscript is not an integer
the warning are all associated with the initialization of the array: if I put '5' instead of 'SIZE' its ok, why? The errors in a I don't get at all. I'm passing a pointer as an arguments, where's the problem? thatnks!
Upvotes: 1
Views: 703
Reputation: 3990
In C89 array-dimensions must known to compile-time, the content of an variable is'nt known at compile-time (also it is const), a define can known at compile-time. a strictly example show like this:
#include <stdio.h>
#define MY_ARRAY_SIZE 5 /* "SIZE" is a bad name for a #define */
typedef int MY_TYPE[MY_ARRAY_SIZE]; /* if possible, use your OWN types for your usecases */
void my_function(int *arr); /* "a" is a bad name for a function */
int main(){
MY_TYPE arr = {1,2,3,4,5};
my_function(arr);
return 0;
}
void my_function(MY_TYPE arr){
int i;
for (i=0; i<sizeof(MY_TYPE)/sizeof*arr; i++)
printf("%d",arr[i]);
}
Upvotes: 0
Reputation: 300827
Your code should presumably be:
void a(int *arr)
{
int *i;
for (i=arr; i < &arr[5]; i++)
printf("%d",*i);
}
but why don't you just write the more understandable:
void PrintArray(int *arr, int size)
{
int i;
for (i=0; i < size; i++)
printf("%d", arr[i]);
}
Upvotes: 1
Reputation: 20225
Try this:
void a(int *arr, int size);
int main(){
int arr[5] = {1,2,3,4,5};
a(arr, 5);
return 0;
}
void a(int *arr, int size){
int i;
for (i=0; i< size; i++)
printf("%d", arr[i]);
}
Upvotes: 0
Reputation: 1482
Arrays in C are indexed from zero. So the last element is arr[4], not arr[5]
Upvotes: 0
Reputation: 272812
Firstly, that should be:
for (i=arr; i<&arr[5]; i++)
^^^
But secondly, i
is not an index, it's a pointer. So your print statement should be:
printf("%d",*i);
Upvotes: 5