c语言定义字符串数组

Python016

c语言定义字符串数组,第1张

C语言字符串数组中的每一个元素均为指针,即有诸形如“ptr_array[i]”的指针。由于数组元素均为指针,因此ptr_array[i]是指第i+1个元素的指针。

例:如二维指针数组的定义为:char *ptr_array[3]={{"asdx","qwer","fdsfaf"},{"44444","555","6666"},{"a78x","q3er","f2f"}}

扩展资料

字符串数组数组元素表示方法:

数组元素的一般形式为:数组名[下标] 其中的下标只能为整型常量或整型表达式。如为小数时,C编译将自动取整。

例如,a[5],a[i+j],a[i++]都是合法的数组元素。数组元素通常也称为下标变量。必须先定义数组, 才能使用下标变量。在C语言中只能逐个地使用下标变量, 而不能一次引用整个数组。

参考资料来源:百度百科—指针数组

方法1,

使用指针数组:

#include

<string.h>

#include

<stdio.h>

#include

<stdlib.h>

int

main()

{

char

*test[]={

"this

is

a

test

",

"test

2

",

"

"}

int

i=0

while(strcmp(test[i],

"

")

!=

0)

puts(test[i++])

system(

"PAUSE

")

return

0

}

这个方法比较简单,

但是问题是这样的话,字符串是常量,无法修改。当然这个问题也可以解决,

比如使用数组赋值,

然后将

char

数组首地址赋值给某一个指针即可。

方法2,使用2维数组:

#include

<string.h>

#include

<stdio.h>

#include

<stdlib.h>

int

main()

{

char

test[][20]={

"this

is

a

test

",

"test

2

",

"

"}

int

i=0

while(strcmp(test[i],

"

")

!=

0)

puts(test[i++])

system(

"PAUSE

")

return

0

}

这样的话,

问题就是

空间的浪费!

C语言并没有字符串这样的类型

是用字符数组存的。

于是 字符串数组 其实就是二维字符数组

比如

char s[10][100]

表示10个字符串, 每个最长100个字节。