Reputation: 45
I have defined a vector
of pointers with weekdays. Later on, I want to sort the days lexicographically
.
I print all the weekdays by using printf("%s", *(wochentag + i));
which works. I want the output of each first letter of each weekday. Later, I want to also access the second, third, ... letter of each word.
By using
printf("%c", *(wochentag + i));`
I get the following warning:
format specifies type 'int' but the argument has type 'char *' [-Wformat].
Here's my code:
int main()
{
static char *wochentag[] = {"Montag", "Dienstag", "Mittwoch", "Donnerstag",
"Freitag", "Samstag", "Sonntag"};
printf("%lu\n", sizeof(wochentag));
printf("%lu\n", sizeof(char));
for (int i = 0; i < 7; i++)
{
printf("%s\n", *(wochentag + i));
}
for (int i = 0; i < 7; i++)
{
printf("%c\n", *(wochentag + i));
}
}
What am I doing wrong?
Upvotes: 1
Views: 1949
Reputation: 23832
In printf("%c\n", *(wochentag + i))
, *(wochentag + i)
is a string, more precisely a dereferenced pointer to a string literal (null-terminated read-only byte array), as you can see in your code, you need "%s"
format specifier.
To print the first char
in each string you would need an extra dereference:
printf("%c\n", **(wochentag + i));
Or for a more reader-friendly notation
printf("%c\n", wochentag[i][0]);
The warning indicating that "%c"
expects an int
is because it is indeed expecting the int
code for the specific character.
A practical example:
int x = 65; //ASCII code for the letter 'A'
printf("%c\n", x);
This will output A
.
Upvotes: 1
Reputation: 793
Your array data type char*[] is a type of double pointer so when you print using %s, it knows that it has address of some array of chars but when you print using only '%c' in printf you have to give the actual character but not the address....so you have to de-reference it twice
Like below
printf("%c", **(wochentag + i));
Hope this answers your problem....peace
Upvotes: 0
Reputation: 134416
The error message is self-explanatory, there is a data type mismatch.
Another syntax of writing *(wochentag + i)
is (wochentag[i])
, which is of type char *
.
Now, passing that to %c
is wrong, as this conversion specification expects a char
type.
If you're interested in only the first char, you have to index into that array, like (wochentag[i][0])
. Something like
printf("%c\n", wochentag[i][0]);
should work.
Upvotes: 2