C语言一维数组和二维数组问题

C语言 码拜 8年前 (2016-01-29) 797次浏览
用vs2013进行C语言编译,按照书本打出来后发现了一个问题,就是运行时输入会很奇怪,无法将全部字符输进去,而且也输不出字符,本人小白一枚,求高手指点,这是本人的码
#include<stdio.h>
#include<string.h>
int main()
{
void sort(char s[][6]);
int i;
char str[10][6];
printf(“input 10 strings:\n”);
for(i=0;i<10;i++)
scanf_s(“%s”,str[i]);
sort(str);
printf(“now,the sequence is:\n”);
for(i=0;i<10;i++)
printf(“%s\n”,str[i]);
}
void sort(char s[10][6])
{
int i,j;
char *p,temp[10];
p=temp;
for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{
strcpy(p,s[j]);
strcpy(s[j],s[+j+i]);
strcpy(s[j+1],p);
}
}
顺带一提,这是按照书本打的,他的运行结果和本人的不一样,怀疑书本错了,请假高手怎么实现这个语句
int i;
char str[10][6];
printf(“input 10 strings:\n”);
for(i=0;i<10;i++)
scanf_s(“%s”,str[i]);
解决方案:30分
修改如下:

#include<stdio.h>
#include<string.h>
void sort(char s[][6], int n);  //第二个参数n是第一维的信息
int main()
{
	int i;
	char str[10][6];
	printf("input 10 strings:\n");
	for (i = 0; i < 10; i++)
		scanf("%6s", str[i]);
	sort(str, 10);
	printf("now,the sequence is:\n");
	for (i = 0; i < 10; i++)
		printf("%s\n", str[i]);
	return 0;
}
void sort(char s[10][6], int n)//这里的第一个维数10,加与不加都是不加的意思。
{
	int i, j;
	//char *p, temp[10];
	//p = temp;
	char tmp[6];
	//冒泡排序
	for (i = 1; i < n; i++)
		for (j = 0; j < n - i; j++)
			if (strcmp(s[j], s[j + 1])>0)
			{
				strcpy(tmp, s[j]);
				strcpy(s[j], s[j + 1]);
				strcpy(s[j + 1], tmp);
			}
}

既然是照着书打的,就不应该打错。

解决方案:10分
scanf_s还需要一个参数指定缓冲区有多大:

scanf_s("%s",str[i], 6);

或用scanf


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C语言一维数组和二维数组问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)