Hello friends,
Please explain the output of the following code:
#include <stdio.h>
int main(void)
{
char *name = "Nikhil";
printf("%d",2[name]);
getchar();
return 0;
}
The output is: 107.
Regards,
Nikhil Khullar
Last edited by nikhilkhullar; 03-12-2010 at 04:39 AM.
Hi,
What happens here is that you are displaying the integer value(ascii) of a char. The character you are displaying is the 'k' in Nikhil, because you are working with an array of characters. In other words: N = 0 in the array. i = 1 in the array etc...
To change the output so that it displays the character instead of the integer value, just change your printf to:"printf("%c", 2[name])"
Hope that helps... ^_^
In ascii, decimal value of 'k' is 107
Odd syntax...
Should beCode:printf("%d",2[name]);
Have you been coding in MIPS or Intel AT&T assembly language?Code:printf("%d",name[2]);They do that.
Last edited by dargueta; 03-12-2010 at 02:51 AM.
sudo rm -rf /
But, Nikhil Khullar wrote, "The output is: 107", he did not say if program had error
True. But I've never seen that syntax before. It's really weird.
EDIT: WTF? It works?! I've been programming in C/C++ for going on seven years now and I've never seen anyone do that before. But apparently it works...
Last edited by dargueta; 03-12-2010 at 02:52 AM. Reason: Grammar
sudo rm -rf /
Don't worry man... ^_^
This surprised me the first time too... was about to post the same as you, but tested first ^_^
I guess you learn something new everyday...
On one hand it logical that it works because eventually its just another way to calculate the address, I mean lets call the original offset start address and the origial start address now will be the offset. On the other hand, in the calculation the index is multiplied by the size of the type, which is derevied by the compiler from the identifier. But here there is no identifier from which the type can be derived... So maybe its some default value by which the offset is multiplied? Or the size of the type is determined by some other means?
@lintwurm: Yeah, really. Only reason why I questioned it was because I've seen the same in Intel assembly language with AT&T syntax, and MIPS assembly language, but not in C. I dunno, it's kinda weird and less readable in my opinion.
@bobdark: Huh? My English is failing me...
Last edited by dargueta; 03-12-2010 at 03:20 AM. Reason: Typo
sudo rm -rf /
aa nvm, what I wrote there is nonsense. My bad...
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks