0

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

no i just want to print the values inside the array by the pointer like *pointer(which prints the value)
@mysqllover You don't print values inside of an array by using pointers. Well, I guess you could, but then it would be printf("%d", *(bae+i)); That's not what you want, however.
that was exactly i wanted
2
#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

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.