C语言 printf() 打印整个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16962144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:36:19  来源:igfitidea点击:

printf() prints whole array

carrayscharprintf

提问by NullPointerException

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

假设我的C 程序中有以下代码:

#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"?

为什么这个输出是整个单词“hello”而不是单个字符“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?

不过,我明白,如果我"%c"在格式化程序中放入 a ,它只会打印一个字母。但是,这个地址中每个字母的内存地址是不同的。请问有人给我解释一下吗?

回答by Rohan

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, printfwill print all characters starting from given address until it finds '\0'.

内存地址不同,但作为其字符数组,它们是连续的。当您传递第一个元素的地址并使用时%sprintf将打印从给定地址开始的所有字符,直到找到为止'\0'

回答by Suvarna Pattayil

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

对于数组,基地址(即数组的地址)是数组中第一个元素的地址。数组名称也充当指针。

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

考虑一排房子(每个房子都是数组中的一个元素)。要识别该行,您只需要第 1 家的地址。您知道每家紧随其后(按顺序)。获取第 1 家的地址,也会给您该行的地址。

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

如果是字符串文字(在声明中定义的字符数组),它们会自动附加\0.

printfprints using the format specifier and the address provided. Since, you use %sit prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

printf使用格式说明符和提供的地址打印。因为,您使用%s它从第一个地址打印(使用算术递增指针)直到 '\0'