C語言基礎 -29 數組_字符數組之定義/初始化

1 單引號實現字符賦值

book@100ask:~/C_coding/CH01$ cat char.c
#include<stdio.h>
#include<stdlib.h>

#define N 3

int main()
{
	char str[N] = {'a','b','c'};
	int i;

	for(i = 0; i < N; i++)
		printf("%c ",str[i]);
	printf("\n");
	exit(0);
}

book@100ask:~/C_coding/CH01$ make char
cc     char.c   -o char
book@100ask:~/C_coding/CH01$ ./char
a b c 

2 雙引號實現字符串賦值。注意:字符串賦值,其存儲空間除了字符串本身外,還包括一個尾零的空間

book@100ask:~/C_coding/CH01$ cat char.c
#include<stdio.h>
#include<stdlib.h>

#define N 3

int main()
{
	char str[N] = "a";
	int i;

	for(i = 0; i < N; i++)
		printf("%c ",str[i]);
	printf("\n");
	exit(0);
}

book@100ask:~/C_coding/CH01$ make char
cc     char.c   -o char
book@100ask:~/C_coding/CH01$ ./char
a   

book@100ask:~/C_coding/CH01$ cat char.c
#include<stdio.h>
#include<stdlib.h>

#define N 3

int main()
{
	char str[N];
	int i;

	gets(str);
	puts(str);
	/*
	for(i = 0; i < N; i++)
		printf("%c ",str[i]);
	printf("\n");
	exit(0); 
	*/
}


book@100ask:~/C_coding/CH01$ make char
cc     char.c   -o char
char.c: In function ‘main’:
char.c:11:2: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
  gets(str);
  ^~~~
  fgets
/tmp/cc3Tg7tU.o: In function `main':
char.c:(.text+0x24): warning: the `gets' function is dangerous and should not be used.
book@100ask:~/C_coding/CH01$ ./char
abcddsdadad
abcddsdadad
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)
book@100ask:~/C_coding/CH01$ ./char
abdc
abdc
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

book@100ask:~/C_coding/CH01$ ./char
ab
ab
book@100ask:~/C_coding/CH01$ ./char
a
a
book@100ask:~/C_coding/CH01$ ./char
abc
abc
book@100ask:~/C_coding/CH01$ ./char
abcd
abcd
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

編譯時提示,屬於gets很危險,因爲它不會檢查邊界,即即使字符數組定義範圍爲3個,當輸入多餘3個字符時,仍然可以執行,即邊界失效。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章