字符串和字符与printf的 [英] Strings and character with printf

查看:126
本文介绍了字符串和字符与printf的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的C程序%C 的使用情况和%S 困惑

 #包括LT&;&stdio.h中GT;    无效的主要()
    {
     CHAR名称[] =湿婆;
     的printf(%S \\ n,名);
     的printf(%C \\ n,*名称);
    }

输出为

 湿婆
小号

为什么我们需要使用指针来显示一个字符%c和不需要的字符串指针

当我使用我得到错误

 的printf(%C \\ N,名);

错误我得到的是

  str.c:在函数'主':
str.c:9:2:警告:格式'%C'型预期'诠释',但参数2的类型'字符*'


解决方案

如果你试试这个:

 #包括LT&;&stdio.h中GT;无效的主要()
{
 CHAR名称[] =湿婆;
 的printf(NAME =%P \\ N,名);
 的printf(&放大器;名称[0] =%P \\ N,&安培;名称[0]);
 的printf(名字印作为%% s处于%S \\ n,名);
 的printf(*名称=%C \\ n,*名称);
 的printf(名称[0] =%C \\ N,名字[0]);
}

输出是:

  NAME = 0xbff5391b
&放大器;名称[0] = 0xbff5391b
名字印为%s是湿婆
*名称= S
命名[0] = S

所以,名字实际上是一个指向字符存储器阵列。如果你试图在阅读的0xbff5391b前四个字节,你会看到的','我','V'和'a'

 位置数据
========= ======0xbff5391b 0x73的'--- GT&;名称[0]
0xbff5391c×69'我'--- GT&;名称[1]
0xbff5391d 0x76'V'--- GT&;命名[2]
0xbff5391e 0x61'一'--- GT&;命名[3]
0xbff5391f为0x00'\\ 0'--- GT&;这是字符串的空终止

要打印您需要通过字符的printf值的字符。该值可作为名字[0]或*名称引用(因为对数组名=&放大器;名称[0])。

要打印所需的指针传递给串的printf字符串。(在这种情况下,名称或&放大器;名称[0]')

I was confused with usage of %c and %s in the following C program

#include<stdio.h>

    void main()
    {
     char name[]="siva";
     printf("%s\n",name);
     printf("%c\n",*name);
    }

Output is

siva
s

Why we need to use pointer to display a character %c, and pointer is not needed for a string

I am getting error when i use

printf("%c\n", name);

Error i got is

str.c: In function ‘main’:
str.c:9:2: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’

解决方案

If you try this:

#include<stdio.h>

void main()
{
 char name[]="siva";
 printf("name = %p\n", name);
 printf("&name[0] = %p\n", &name[0]);
 printf("name printed as %%s is %s\n",name);
 printf("*name = %c\n",*name);
 printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data
=========   ======

0xbff5391b    0x73  's'  ---> name[0]
0xbff5391c    0x69  'i'  ---> name[1]
0xbff5391d    0x76  'v'  ---> name[2]
0xbff5391e    0x61  'a'  ---> name[3]
0xbff5391f    0x00  '\0' ---> This is the NULL termination of the string

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').

这篇关于字符串和字符与printf的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆