简体   繁体   中英

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:

  • hello
  • ello
  • llo
  • lo
  • o

But I want it to print;

  • h
  • e
  • l
  • l
  • o

I am unable to do it by using the variable q inside printf. Thanks

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 .

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++));
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM