C语言读入多个字符串(不含空格)的方法

方法一:定义二维字符串数组

//方法一:直接定义字符串数组

#include<stdio.h>

int main(){
int len = 100;//len是每个字符串最大的长度
//输入字符串的个数
int n;
scanf("%d", &n);
//定义字符串数组
char p[n][len];
//读入字符串数组
for(int i = 0; i < n; i++){
scanf("%s", &p[i][0]);
}
//输出字符串数组
for(int i = 0; i < n; i++){
printf("%s \n", &p[i][0]);
}
return 0;
}



方法二:定义字符串指针数组

/*方法二:定义字符串指针数组,即数组中的指针指向字符串,
并需要给数组中的每个指针分配动态内存*/

#include<stdio.h>
#include<stdlib.h>

int main(){
int len = 100;//len是每个字符串最大的长度
//输入字符串的个数,
int n;
scanf("%d", &n);
//定义字符串指针数组,并给每个指针分配动态内存
char *p[n];
for(int i = 0; i < n; i++){
p[i] = (char*)malloc(len * sizeof(char));
}
//读入字符串数组
for(int i = 0; i < n; i++){
scanf("%s", p[i]);
}
//输出字符串数组
for(int i = 0; i < n; i++){
printf("%s \n", p[i]);
}
//释放内存
for(int i = 0; i < n; i++){
free(p[i]);
}
return 0;
}