Reputation: 1
#include<stdio.h>
#include<string.h>
void string1(char *q)
{
while(*q)
{
printf(q++);
printf("\n");
}
}
main()
{
char name[]= "hello";
char *p=name;
string1(p);
}
which prints:
But I want it to print;
I am unable to do it by using the variable q inside printf. Thanks
Upvotes: 0
Views: 97
Reputation: 7769
You need to specify the first argument of printf()
By doing this:
printf(q++);
The application is behaving as if you want to print a string (because it keeps printing until it reaches \0
), so what you are doing is equivalent to this;
printf("%s",q++);
But what you actually want is printing only the char at position q
:
printf("%c",q++); // Prints only the char at q, then increment q
Upvotes: 1
Reputation: 33029
You should always use a format string with printf
. Passing strings with unknown values into the printf
function can result in an uncontrolled format string vulnerability. Printing a c-string with printf
should be done like this: printf("%s", string_pointer);
That said, to print one character at a time you can use the %c
formatter:
while(*q) {
printf("%c\n", *(q++));
}
Upvotes: 2
Reputation: 4433
Your sentence: printf(q++);
is wrong.
You have to print a character, only:
printf("%c", *g++);
A better option:
putchar(*g++);
In general, take in account that:
g
is the adress of an array of characters. g
, it is necessary to use the operator *
, this way: *g
. The modifier "%c"
in printf()
gives you the possibility of printing a datum of type char
.
Upvotes: 3