Search code examples
cstringpointersdereference

Assigning pointer values


I'm a beginner to C language and don't understand presumably easy concepts of the pointer, string, etc.

The source code is as follows.

#include<stdio.h>
int main(void){
char *p="Internship ";
printf("%s\n", p);
printf("%c\n", *p++);
printf("%c\n", *p+2);
printf("%c\n", *(p+6));
printf("%c\n", *++p);
printf("%c\n", *p--);
printf("%c\n", *(p+5));
printf("%c\n", *p);
return 0;
}

The output is

Internship                                                                                                                                    
I                                                                                                                                             
p                                                                                                                                             
h                                                                                                                                             
t                                                                                                                                             
t                                                                                                                                             
s 
n

Please explain the code and output in detail as much as possible. You'll help me a lot. Thank you in advance.


Solution

  • It's a confusing mix of pointer arithmetic and value arithmetic, combined with prefix and postfix increment/decrement.

    #include<stdio.h>
    int main(void){
    char *p="Internship "; /* creates a pointer p that points to the memory area
                              that contains the String Internship */
    printf("%s\n", p);     /* This prints the string that p points to */
    printf("%c\n", *p++);  /* This prints the character that p points to (I)
                              and then increments the address contained in p */
    printf("%c\n", *p+2);  /* This prints the character that p points to (n),
                              but adds 2 to the value 'n' + 2 = 'p' (in ASCII) */
    printf("%c\n", *(p+6)); /* This prints the character 6 ahead of what p points
                              to (h) */
    printf("%c\n", *++p);  /* This prints the character the successor of p's value
                              points to (t). p is incremented */
    printf("%c\n", *p--);  /* This prints the character that p points to (t), and
                              then decrements the value of p */
    printf("%c\n", *(p+5)); /* This prints the character 5 ahead of the character
                              p points to (s), but doesn't change p */
    printf("%c\n", *p);    /* This again prints the character p points to (n) */
    return 0;
    }
    

    I hope my comments in your code help you to understand what happens.