C语言二级指针的问题
#include<stdio.h>voidsort(char**p);intmain(){char*a[7]={"mouth","my","crystle","orang...
#include <stdio.h>
void sort(char **p);
int main()
{
char *a[7]={"mouth","my","crystle","orange","unity","school","office"};
int i;
sort(a);
for(i=0;i<7;i++)
{
printf("%s\n",a[i]);
}
}
void sort(char **p)
{
int i,j;
char temp;
for(i=0;i<7;i++)
{
for(j=0;j<10;j++)
{
if(p[i][j]>p[i][j+1])
{
temp=p[i][j];
p[i][j]=p[i][j+1];
p[i][j+1]=temp;
}
}
}
}
为什么程序奔溃?求大神能帮忙改一下代码!! 展开
void sort(char **p);
int main()
{
char *a[7]={"mouth","my","crystle","orange","unity","school","office"};
int i;
sort(a);
for(i=0;i<7;i++)
{
printf("%s\n",a[i]);
}
}
void sort(char **p)
{
int i,j;
char temp;
for(i=0;i<7;i++)
{
for(j=0;j<10;j++)
{
if(p[i][j]>p[i][j+1])
{
temp=p[i][j];
p[i][j]=p[i][j+1];
p[i][j+1]=temp;
}
}
}
}
为什么程序奔溃?求大神能帮忙改一下代码!! 展开
1个回答
展开全部
char *a[7]={"mouth","my","crystle","orange","unity","school","office"};
a数组里的char*指向的字符串空间是不可修改的,也就没法被排序
还有后面的冒泡排序是错误的
给你改了下:
#include <stdio.h>
void sort(char **p);
int main()
{
char sa[7][10] = { "mouth", "my", "crystle", "orange", "unity", "school", "office" }; //字符串可读写
char *a[7] = {sa[0],sa[1],sa[2],sa[3],sa[4],sa[5],sa[6]}; //指向可读写的字符串
int i;
sort(a);
for (i = 0; i<7; i++)
{
printf("%s\n", a[i]);
}
}
void sort(char **p)
{
int i, j,k,l; //k,l
char temp;
for (i = 0; i<7; i++)
{
for (l=0,j = 0; p[i][j]; ++j) //先求出字符串的长度
++l;
for (k = 0; k<l; k++) //冒泡排序
{
for(j=0;j<l-k-1;++j)
if (p[i][j]>p[i][j + 1])
{
temp = p[i][j];
p[i][j] = p[i][j + 1];
p[i][j + 1] = temp;
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询