How did this pointer get resolved in this C code? -
I have some code (below) where I am specifying the address of an integer array for an indicator. I am telling two ways and expecting two separate outputs, but in both cases the output is similar.
main () {int a [] = {11,2,3}; Int * p = & amp; A; Printf ("% d", * (P +1)); } This should give me some garbage because p is pointing to the next 1D array main ( ) {Int a [] = {11,2,3}; Int * p = a; Printf ("% d", * (P +1)); } It should print 2 . Although the print of both of these tasks 2 It is not what I expected that someone could tell what is happening?
Can someone tell me how I point the pointer to the whole array just as compared to the different element.
If you compile the program first, you will receive a compiler warning:
Warning: Getting Started with Incompatible Notifier Type Because the type of p is the indicator for the integer, but the and type It is OK to compile the other program, because again the p type int * and one type < / Code> int [] '(i.e., full Array) but in C, you can assign the right to an integer pointer to an integer array. The value of the pointer is assigned to the initial address of the array. When you define an array with square brackets in C, the array is placed immediately in the stack or data section, so its initial address array is similar to the address of the ARA variable! It is different from the arrays created with malloc . What this means for you: Assuming that the variable a address is allocated on 4e78ccba, this means that & amp; A 4e78ccba but in C, the value of a is given when one pointer is given / defines the array according to the definition, so it also 4e78ccba. Then, if you set things with Molok things, then it will be different (try !!) and by the way, pay attention to the warnings. :) This is an interesting question because C is typed in such a weak way, only you had a warning in the first case. An integer typed language does not like an integer mixer with an integer array indicator.
ADDENDUM Here some code is shown how you can actually differentiate the pointer from the first element and for the entire array Notifier : #include & lt; Stdio.h & gt; Int main () is an array of {/ * a ints, but it can be used as an indicator for int * / int a [] = {11, 2, 3}; / * Use as an integer indicator * / int * p = a; Printf ("% d \ n", * (P + 1)); / * Now here's how to create a pointer for the array! * / Int (* q) [] = & amp; A; Printf ("% d \ n", (* q) [2]); Return 0; } This program outputs
2 3
Comments
Post a Comment