简体   繁体   English

printf()打印整个数组

[英]printf() prints whole array

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. 但我明白,如果我在格式化程序中输入"%c" ,它将只打印一个字母。 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' . 当您传递第一个元素的地址并使用%sprintf将打印从给定地址开始的所有字符,直到找到'\\0'

Incase of arrays , the base address (ie 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. 要识别行,您只需要第一个房子地址。您知道每个房子后面是下一个(顺序)。获取第一个房子的地址,也会给您行的地址。

Incase of string literals(character arrays defined at declaration), they are automatically appended by \\0 . 包含字符串文字(在声明中定义的字符数组),它们会自动附加\\0

printf prints using the format specifier and the address provided. printf使用格式说明符和提供的地址进行打印。 Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\\0' 因为,你使用%s它从第一个地址打印(使用算术递增指针)直到'\\ 0'

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

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