-3

I have written the code in C language,

#include<stdio.h>

int main(void)
{
    char c[]="Suck It Big";
    char *p=c;
    printf("%c\n",p);
    printf("%c\n",p[3]);
    printf("%c\n",++p);
    printf("%d\n",p);
    printf("%d\n",p[3]);
}

The output to this code i get is:
Output

I copied the strange characters on line 1 and 3 of the output and pasting it on the editor gives this "DLE". Can anybody explain the meaning of this.

Community
  • 1
  • 1
  • 2
    You are trying to print a pointer as a `char`. That is undefined behaviour. – kaylum Apr 12 '20 at 07:24
  • What about "DLE" and ? – Prateek Tewary Apr 12 '20 at 07:25
  • What about it? It's undefined behaviour. There is no point trying to explain undefined behaviour. – kaylum Apr 12 '20 at 07:26
  • @kaylum .. i checked the DLE thing.. it is maybe an ascii character which stands for DLE ( Data link escape ).. i think there is more to the answer. – Prateek Tewary Apr 12 '20 at 07:28
  • There could be an ascii `16` in there some where. But that is coming from garbage data and is by chance and not by design. On a different system or on a different compiler or if the weather changes the result of undefined behaviour may change. – kaylum Apr 12 '20 at 07:35
  • 1
    [Does “Undefined Behavior” really permit *anything* to happen?](https://stackoverflow.com/questions/32132574/does-undefined-behavior-really-permit-anything-to-happen) – kaylum Apr 12 '20 at 07:37

1 Answers1

1

All printf() calls you use are incorrect, except for the second one, because either the relative argument or the used conversion specifier is wrong.

This invokes Undefined Behavior:

Quote from C18, 7.21.6.1/9 - "The fprintf function":

"If a conversion specification is invalid, the behavior is undefined.288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."


printf("%c\n",p);

When you attempt to print the value of the object the pointer points to, you have to use the dereference operator (*) preceding the pointer object. Else you attempt to print the value of the pointer - the address of the object the pointer point to. And due to this operation, you using the wrong conversion specifier of %d instead of %p to print the value of a pointer.


The corrected program is:

#include<stdio.h>

int main(void)
{
    char c[]= "Suck It Big";
    char *p = c;
    printf("%c\n", *p);              // Prints the first element of array c.
    printf("%c\n", p[3]);            // Prints the fourth element of array c
    printf("%c\n", *(++p));          // Prints the second element of array c
    printf("%p\n", (void*) p);       // Prints the address held in p / first element of c.
    printf("%p\n", (void*) &p[3]);   // Prints the address of the fourth element of c.
}

Note, that the cast to void* is necessary to make the program conforming to the C standard.

Output:

S
k
u
0x7fff1d3a133d  // Address defined by system
0x7fff1d3a1340  // Address defined by system