printf()的打印整个数组 [英] printf() prints whole array

查看:4703
本文介绍了printf()的打印整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有以下code在我的 C程序

 的#include<&stdio.h中GT;无效PrintSomeMessage(字符* P);INT主(INT ARGC,CHAR *的argv []){
    焦炭ARR [10] =你好;
    PrintSomeMessage(安培;常用3 [0]);
    返回0;
}无效PrintSomeMessage(字符* P)
{
    的printf(P:%S,P);
}

为什么这个输出将是整个单词你好,而不是一个单独的字符h的

我明白了,虽然,如果我把一个%C在格式化,将打印只是一个字母。但尽管如此,在内存地址中该地址的每个字母是不同的。请,有人解释给我听?


解决方案

  

但尽管如此,内存地址在该地址中的每个字母都是不同的。


内存地址是不同的,但它的字符数组他们是连续的。当你通过第一个元素的地址,并使用%S 的printf 将打印的所有字符从指定的地址开始,直到找到'\\ 0'

Let's assume I have the following code in my C program:

#include <stdio.h>

void PrintSomeMessage( char *p );

int main(int argc, char *argv[]) {
    char arr[10] = "hello";
    PrintSomeMessage(&arr[0]);
    return 0;   
}

void PrintSomeMessage(char *p)
{
    printf("p: %s",p);
}

Why the output of this would be the whole word "hello" instead of a single character "h"?

I understand, though, that if I put a "%c" in the formatter, it will print just a single letter. But still, the memory address for each letter in this address is different. Please, someone explain it to me?

解决方案

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

这篇关于printf()的打印整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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