0
#include<stdio.h>
int main()
{
char str[3][10]={
                    "vipul",
                    "ss",
                    "shreya"
};

Why this won't work:

printf("%s",str[1][0]);

If i want to access str whereas

printf("%s",&str[1][0]);

or this would do it perfectly

printf("%s",str[1]);

Can anyone explain ? Why is the first code giving an error

prog.c: In function ‘main’:
prog.c:9:5: error: format ‘%s’ expects argument of type ‘char *’, but 
                   argument 2 has type ‘int’ [-   Werror=format]
cc1: all warnings being treated as errors

Why does the argument has type int?

akira
  • 6,050
  • 29
  • 37

5 Answers5

3

Well

str[1] is a char* and str[1][0] is a char.
But when you use %s, printf() expect a pointer so you try to cast the char into a pointer.

So your char is promoted to an int.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Alexis
  • 2,149
  • 2
  • 25
  • 39
3
printf("%s",str[1][0]);

The problem is in this line. When For %s format specifier, printf() expects a pointer to a null terminated string. Whereas str[1][0] is simply a char (specifically the first s in "ss"), which is promoted to int (default argument promotions). That's exactly what the error message says.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

It is said in the error:

format ‘%s’ expects argument of type ‘char *’

and your argument str[1][0] is a char, not the expected char *. In C, a char is treated as an int.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
0

In first case printf("%s",str1[1][0]); you are passing single character to printf function and format specifier that you use it %s. For %s printf function expects string of character and not character.So it gives error.
As in 1st printf function you are specifying %s and you are passing character, argument promotion will takes place and char will promoted to int.

•The default argument promotions are char and short to int/unsigned int and float to double
•The optional arguments to variadic functions (like printf) are subject to the default argument promotions

More on Default argument promotion and here.

Community
  • 1
  • 1
Rohan
  • 3,068
  • 1
  • 20
  • 26
0

on your line error:

 printf("%s",str[1][0]);

you try to print a string where you have a character ("%c" in printf)

so to only print one of ur 2D array you would have to do something like that:

  int main()
  {
  int i;
  char str[3][10]=
  {
  "vipul",
  "ss",
  "shreya"
  };
  i = 0;
  while(str[0][i] != '\0')
  {
  printf("%c",str[0][i]);
  i++;
  }
  }

which is pretty ugly ^^

instead you could print all ur 2D array with 3 single iteration with that:

 int main()
 {
 int i;
 char str[3][10]=
 {
 "vipul",
 "ss",
 "shreya"
 };
 i = 0;
 while(i < 3)
 {
 printf("%s\n",str[i]);
 i++;
 }
 }
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32