当前位置: 代码迷 >> C语言 >> 用指针数组的方法输入字符串的问题
  详细解决方案

用指针数组的方法输入字符串的问题

热度:141   发布时间:2006-06-04 22:00:00.0
用指针数组的方法输入字符串的问题

我编写了一个函数,是用指针数组的方法输入字符串,代码是这样:
main()
{char *str[5];
int i,j;
printf("enter string:");
for(i=0;i<5;i++)
scanf("%s",str[i]);
printf("output:");
for(i=0;i<5;i++)
printf("%s",str[i]);
}

可是在运行时,在输入完第五行时Windows提示错误,不知可否用此方法输入字符串.如果可以请问,此代码有否错误.

搜索更多相关的解决方案: 指针  字符  输入  str  main  

----------------解决方案--------------------------------------------------------

未给指针分配可读写空间!


----------------解决方案--------------------------------------------------------
那怎样给指针分配可读写空间呢?
----------------解决方案--------------------------------------------------------
for(i=0;i<10;i++)
str[i]=(char *)malloc(sizeof(char)*20);

判断下是否申请成功

----------------解决方案--------------------------------------------------------

诶,本打算不发言了,但看见美女我就控制不住啊,我写一个吧

#include <stdio.h>
#include <string.h>

#define N 10

static void Initial(char **s);
static void Input(char *s[]);
static void Sort(char *s[]);
static void Output(char *s[]);

int main(void)
{
char *s[5];

Initial(s);

Input(s);

Sort(s);

Output(s);

return 0;
}

static void Initial(char **s)
{
int i;

for (i = 0; i < 5; i++)
{
if (((s[i] = (char*)malloc(sizeof(char) * N))) == NULL)
{
exit(1);
}
}
}

static void Input(char *s[])
{
int i;

for (i = 0; i < 5; i++)
{
scanf("%s", s[i]);
}
}

static void Sort(char *s[])
{
int i, j;
char t[N];

for (i = 0; i < 4; i++)
{
for (j = i + 1; j < 5; j++)
{
if (strcmp(s[i], s[j]) > 0)
{
strcpy(t, s[i]), strcpy(s[i], s[j]), strcpy(s[j], t);
}
}
}
}

static void Output(char *s[])
{
int i;

printf("The after sort:\n");
for (i = 0; i < 5; i++)
{
printf("%s\n", s[i]);
}
}


















----------------解决方案--------------------------------------------------------
1、先把定义的字符串数组指向NULL,不然是野指针了;
2、就是楼上老头子说的那样分别分配空间;
3、记得释放空间;
----------------解决方案--------------------------------------------------------
在运行时,在输入完第五行时Windows提示错误,这不说明前4个字符串已经输入了吗,如果按你说的方法,在什么地方判断呢?具体代码……
----------------解决方案--------------------------------------------------------
以下是引用han2y在2006-6-4 22:23:00的发言:
在运行时,在输入完第五行时Windows提示错误,这不说明前4个字符串已经输入了吗,如果按你说的方法,在什么地方判断呢?具体代码……

在运行时,在输入完第五行时Windows提示错误 ==》 这个是不同编译器的处理方法不同,你的编译器等到输入第5个是才发现字符串数组没有分配内存,所以这时候才出现错误。换成其他编译器,可能刚输入一两个就出现错误。


----------------解决方案--------------------------------------------------------
  相关解决方案