Pushp Sra
Pushp Sra

Reputation: 634

C Strings, Pointers, Puts

I have been studying a code on Programming in C lately. I got stuck here while dealing with two dimensional strings and pointers. Also the functions printf(), putchar(), and puts() are confusing! Please help me out with the following snippet:

#include<stdio.h>

int main()
{
    char wer[3][4]= {"bag", "let", "bud"};
    char (*ptr)[4]=wer;
    printf("%d   %d   %d\n",ptr, ptr+1, ptr+1); // points to bag, let and bud respectively 
    printf("%d   %d   %d\n",wer, wer+1, wer+1); // points to bag, let and bud respectively

    printf("%d   %d   %d\n", (*ptr), (*ptr+1), (*ptr +2)); // points to b,a,g respectively

    printf("%s\n",*(ptr+1)); //prints let
    printf("%s\n", (ptr+1)); //prints let
    printf("%s\n", (*ptr +1)); //prints ag


    puts(*(ptr+1)); //prints let
    //puts((ptr+1)); //gives error
    puts((*ptr+1)); //prints ag


    putchar(**(ptr+1));//prints l
    putchar(*(*ptr +1));//prints a

    return 0;
}

I want to know why do *(ptr+1) and (ptr+1) both work for printf while (ptr+1) gives an error for puts. Also I know that putchar takes an integer argument. Why do we use double pointer here?

Upvotes: 1

Views: 777

Answers (1)

blatinox
blatinox

Reputation: 843

Your ptr variable is of type char (*)[4] (a pointer to char array). The prototype of puts is:

int puts(const char *s);

So, as your compiler probably says, puts expects a pointer on char but you give an argument of type char (*)[4].

I want to know why do *(ptr+1) and (ptr+1) both work for printf while (ptr+1) gives an error for puts.

The argument types are not checked on the call to printf (probably because printf takes variadic arguments). Add -Wall in your CFLAGS to add more warnings and your compiler should emit a warning about this.

Also I know that putchar takes an integer argument. Why do we use double pointer here?

You dereference ptr twice to get a char (you can also do (*ptr)[1]). This char is implicitly cast into int when you call putchar.

Upvotes: 1

Related Questions