c编程书说我的字符串必须为空终止以使用printf打印它,但仍然以下程序打印字符串尽管它是非空终止!
#include <stdio.h>
#include <stdlib.h>
int main(){
int i ;
char str[10] ;
for(i = 0 ; i < 10 ; i++ ) {
str[i] = (char)(i+97) ;
}
printf("%s",str) ;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用codeblocks IDE.
好吧,我有一个奇怪的问题printf().它在屏幕上输出垃圾.我想这与记忆有关.看一看:
char string1[] = "SAMPLE STRING";
char string2[20]; // some garbage in it
/* let's clear this madness*/
int i = 0;
for (i; i < 20; i++) string2[i] = ' '; // Space, why not.
printf("output: %s", string2);
Run Code Online (Sandbox Code Playgroud)
OUTPUT
output: ???????????????????????????SAMPLE STRING
// ten spaces and random characters, why?
Run Code Online (Sandbox Code Playgroud) 由于一个C字符阵列需要一个空终止,下面的代码打印4个一个 S和一些乱码.
char y[4] = {'a', 'a', 'a', 'a'};
printf("y = %s\n", y);
Run Code Online (Sandbox Code Playgroud)
输出:
y = aaaa?
Run Code Online (Sandbox Code Playgroud)
但是,以下代码不会生成垃圾字符.
char y[4] = {'a', 'a', 'a', 'a'};
char z[4] = {'b', 'b', 'b'};
printf("y = %s\n", y);
printf("z = %s\n", z);
Run Code Online (Sandbox Code Playgroud)
输出:
y = aaaa
z = bbb
Run Code Online (Sandbox Code Playgroud)
我知道第四个字符z是使用null终止符自动初始化的.我猜也是如此,y并z在内存中彼此相邻分配.
但是,在这种情况下,C如何正确打印4 a而不是前者?它是否确定下一个字节已经分配给另一个变量,所以它应该再停止打印了?