Yash Javeri
Yash Javeri

Reputation: 1

void*,pointers of strings and characters

#include<stdio.h>
#include<conio.h>
void main() 
{
   char cr[] = "Yash";
   clrscr();
   printf("%p\n",(void*)cr);
   printf("%p\n",cr);
   printf("%p\n",&cr);
   printf("%p\n",&cr[0]);
   printf("%p\n",cr[0]);
   printf("%p\n",(void*)cr[0]);

   printf("%c\n",&cr[0]);
   printf("%s\n",&cr);
   printf("%c\n",(void*)cr[0]);
   printf("%s\n",(void*)cr);
   getch();
}

Output:

FFEE
FFEE
FFEE
FFEE
0059
0059
ε
Yash
Y
Yash

Question: I fail to understand exactly the output which I get in this code. Can somebody please explain each output why is it the way it is. Especially why does printf("%c",&cr[0]); give some sought of ε this weird or may be be null symbol? And why are outputs of (void*)cr[0] and cr[0] different from the other 3 in the half of %p? If they are just addresses then why different?(I am really really sorry for the last minute changes I made:/)

Upvotes: 0

Views: 127

Answers (1)

chux
chux

Reputation: 153498

explain each output

UB is undefined behavior: Anything may happen. "%p" expects a void*. pointers to characters and void* have same representation.

char cr[] = "Yash";
printf("%p\n",(void*)cr);     // OK:  address of CR[0]
printf("%p\n",cr);            // OK:  address of CR[0]  
printf("%p\n",&cr);           // UB,  &cr is neither a void * or pointer to a character
printf("%p\n",&cr[0]);        // OK:  address of CR[0]  
printf("%p\n",cr[0]);         // UB   cr[0] is neither a void * or pointer to a character
printf("%p\n",(void*)cr[0]);  // UB,  conversion to void* from arbitrary integer

"%s" expects a char* to a valid string

printf("%s\n",&cr);           // UB,  Not a `char *`
printf("%s\n",(void*)cr);     // OK

"%c" expects a int, converts that to a unsigned char and prints that character.

printf("%c\n",&cr[0]);        // UB, pointer passed as int
printf("%c\n",(void*)cr[0]);  // UB, pointer passed as int

why does printf("%s",&cr); give ....

printf("%s",&cr); --> printf expects &cr to be a valid pointer to a string. It is not. Results: undefined behavior - anything may occur.

why are outputs of (void*)cr[0] and cr[0] different from the other 3 in the half of "%p

printf("%p\n",(void*)cr[0]); and printf("%p\n",cr[0]); are UB.


Explaining output when UB occurs is not productive until one clearly understands why explaining UB is not generally useful.

Upvotes: 3

Related Questions