简体   繁体   English

指向字符数组的C指针

[英]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
  • lo
  • o Ø

But I want it to print; 但我要打印;

  • h H
  • e Ë
  • l
  • l
  • o Ø

I am unable to do it by using the variable q inside printf. 我无法通过在printf中使用变量q来做到这一点。 Thanks 谢谢

Your sentence: printf(q++); 您的句子: 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是字符数组的地址。
  • To access the first character pointed by g , it is necessary to use the operator * , this way: *g . 要访问g指向的第一个字符,必须使用运算符* ,即*g

The modifier "%c" in printf() gives you the possibility of printing a datum of type char . printf()的修饰符"%c"使您可以打印char类型的数据。

You should always use a format string with printf . 您应该始终将格式字符串与printf Passing strings with unknown values into the printf function can result in an uncontrolled format string vulnerability . 将具有未知值的字符串传递给printf函数可能会导致不受控制的格式字符串漏洞 Printing a c-string with printf should be done like this: printf("%s", string_pointer); 使用printf打印c字符串应该像这样完成: printf("%s", string_pointer);

That said, to print one character at a time you can use the %c formatter: 也就是说,要一次打印一个字符,可以使用%c格式化程序:

while(*q) {
    printf("%c\n", *(q++));
}

You need to specify the first argument of printf() 您需要指定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; 该应用程序的行为就好像您要打印一个字符串一样(因为它一直打印直到到达\\0 ),因此您所做的等同于此。

printf("%s",q++);

But what you actually want is printing only the char at position q : 但是,您真正想要的只是在位置q处打印char:

printf("%c",q++); // Prints only the char at q, then increment q

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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