如何在程序中将数组存储在内存中

如何在程序中将数组存储在内存中

本文介绍了如何在程序中将数组存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此程序中将数组存储在内存中?这里发生了什么?如何理解c中的这种行为?(它是未定义/未指定/实现的行为).

How is an array stored in memory in this program? What happened here?How to understand this behaviour in c?(is it undefine/unspecified/implementation behaviour).

#include <stdio.h>

int main()
{
char a[5] = "world";
char b[16] = "haii how are you";

printf("string1 %s\nstring2 %s\n", a, b);

return 0;
}

输出:

user@toad:~$ gcc -Wall simple.c
user@toad:~$ ./a.out
string1 world
string2 haii how are youworld
user@toad:~$

但这很好用.

char a[5] = "world";
char b[17] = "haii how are you?";

推荐答案

第一个代码段中的字符串都不以null结尾.它们只是字符数组,而不是以null结尾的字符串文字.
带有%s说明符的printf期望以空终止的字符串作为其参数.传递错误的参数类型将调用未定义的行为.

Both of the string in the first snippet is not null terminated. They are just character arrays, not null terminated string literals.
printf with %s specifier expects a null terminated string as its argument. Passing wrong type of argument will invoke undefined behavior.

printf将字符串写入标准输出,直到遇到'\0'字符为止.如果没有'\0',它将读取数组之外的内容.由于ab并非以null终止,因此可能是在将b写入终端printf之后继续搜索'\0'并在字符串a之后找到它的情况.

printf write the string to the standard output till it encounters a '\0' character. In case of absence of '\0' it will read past the array. Since a and b are not null terminated, it could be the case that after writing b to the terminal printf continues to search for '\0' and it founds it after the string a.

这篇关于如何在程序中将数组存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:14