Bhats
Bhats

Reputation: 1

C pointer to character array

I would like to pass a character pointer ( to an array) to a function which will print the letters one by one. For example I am using the code below:

#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

Answers (3)

CMPS
CMPS

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

DaoWen
DaoWen

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

pablo1977
pablo1977

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.
  • To access the first character pointed by 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

Related Questions