Reputation: 59
Im new to the C programming language. I have a pointer array with 2 elements. I want to print the values inside the array. The code I have written
#include<stdio.h>
int main ()
{
int *bae[] = {10,12};
int i;
for(i=0;i<2;i++) {
printf("%d",*bae[i]);
}
return 0;
}
When I run this code it gave me warning like:
warning: (near initialization for 'bae[0]') [enabled by default]
warning: initialization makes pointer from integer without a cast [enabled by default]
warning: (near initialization for 'bae[1]') [enabled by default]
Hope you could help me in finding the solution
Upvotes: 0
Views: 300
Reputation: 1000
int *bae[] = {10,12};
It means bae is an array of integer pointers.
printf("%d",*bae[i]);
The above statement is equal to *(bae + i). so it will try to access the value at the address 10 and 11 which leads to undefined behavior.
Upvotes: 0
Reputation: 9270
bae
is an array of int-pointers at the moment. If you want just an array, it should be int bae[] = {10, 12};
Then, you can printf("%d", bae[i]);
What the warning is saying ("initialization makes pointer from integer without a cast") is that you are converting 10
and 12
into int*
when storing them in bae
.
EDIT: If you really want to use a pointer array, then you could do something like this (though not advisable, and in no way better than my previous answer):
#include<stdio.h>
int main ()
{
int ten = 10;
int twelve = 12;
int *bae[] = { &ten, &twelve };
int i;
for(i=0;i<2;i++) {
printf("%d",*bae[i]);
}
return 0;
}
This would now print 10
and 12
.
Upvotes: 2
Reputation: 5305
#include <stdio.h>
int main ()
{
int bae[] = {10,12};
int i;
for(i=0; i<2; i++) {
printf("%d\n", bae[i]);
}
return 0;
}
produces the output:
10
12
Upvotes: 2