I wrote this code.
Why does **b give error? And why does *b give 10? Shoudn't it give a pointer?Code:int a[1][2]={{10,1}};int *b[1]={{10,1}}; int main(){ printf("%d",**a); //prints 10 printf("%d",**b); //gives error printf("%d",*b); //gives 10 }
I wrote this code.
Why does **b give error? And why does *b give 10? Shoudn't it give a pointer?Code:int a[1][2]={{10,1}};int *b[1]={{10,1}}; int main(){ printf("%d",**a); //prints 10 printf("%d",**b); //gives error printf("%d",*b); //gives 10 }
> Why does **b give error?
Because 10 isn't a valid memory address on your system.
> And why does *b give 10?
Because that's what you stored in the array to begin with.
If you want to pretend that 10 is a pointer, then later on pretend that the pointer is an int, you get back to where you started.
> Shoudn't it give a pointer?
Perhaps you should use a decent compiler that will give you warnings about incompatible types in assignment.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I am a beginner in c and I'm not understanding what you said.
I declaredwhich is an array of pointers to int. So when I assign itCode:int *b[], shouldn't *b give a pointer to where first element of the first array in b, ie 10, is stored, not 10 itself? Also, adding 1 to *b refers to first element of second array in b(not present here). How do I refer to the second element of first array in b, ie 1 ?Code:{{10,1}}
Nope. Incidentally, what you're doing is initialising, not assigning.
The initialisers of an array of pointers initialise the pointers with the supplied values. The additional braces don't change that so
is equivalent toCode:int *b[1]={{10,1}};
which has the same net effect (including warnings from your compiler, if used with appropriate non-default warning levels) asCode:int *b[1]={10,1};
The type of shorthand you expect (initialisers that look like arrays leading to pointers being initialised to the first elements in those arrays) isn't what you get.Code:int *b[2]; b[0] = 10; b[1] = 1;
How could it have the same effect? b should have 1 element but you wrote 2.
Let's say I wrote
then b[0] should be 10, b[1] is 1 and so on. But b[1] is 5 and that's it.Code:int *b[]={{10,1},{5,3}};
Also if I try
it works as I wrote before. Isn't "ab" just a character array?Code:char *b[]={"ab","cde"};
I am a bit confused.
Perhaps you would be less confused if you stored integers in an integer array, and printed them as integers.
Instead of all this hooky 'ints-as-pointers' rubbish which won't even compile on a modern compiler.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.