关于C语言指针指向字符数组的问题?

char str0[3][20],*p,*q;
q=str0;
printf("please write %d string:\n",N);
for(p=q;p<q+N;p++) gets(p);
for(p=q;p<q+N;p++) puts(p);

这是标准答案上的,怎么跟我需要要的结果不一样
输入:
a
b
c
得到:
abc
bc
c
我想要的是:
a
b
c
补充说明下N为3

这个问题说起来简单,也复杂;首先需要理解数组声明后的内存分配,str0[3][20],分配连续60个字节的空间,str0[0]指向起点,str0[1]指向第21个字符,也就是str0+20;以此类推;
你输入的时候是从开始连续放到这个存储空间,也就是str0+0、str0+1、str0+2;
输出时从str0+0开始,字符串是以0结束的(表述为'\0'),后面知道此之后才是'\0',所以首先输出abc;然后从str0+1开始输出,结果为bc;然后输出就是c了。
现在的p++是指向下一个字符(移动一个字节),而不是一个字符串。

按照你想要的应该输入的时候,存储地址应为str0[0]、str0[1]、str0[2];输出也同样
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-23
程序写错了,指针所指的位置不对,改成这样:
void main()
{
int N=3;
char str0[3][20],*p,*q; ;
q=str0[0];
printf("please write %d string:\n",N);
for(p=q;p<q+N*20;p+=20) gets(p);
for(p=q;p<q+N*20;p+=20) puts(p);
system("pause");
return;
}

这样写的程序最多接受3个字符串,每个字符串最大长度为20,不如使用c++里的vector和string,多大多长都可以
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void main()
{
int N=3; //N可以为任意值
vector<string> vec;
string temp;
printf("please write %d string:\n",N);
for(int i=0;i<N;i++){cin>>temp;vec.push_back(temp);}
for(int i=0;i<N;i++) cout<<vec[i]<<endl;
system("pause");
return;
}本回答被提问者采纳
相似回答