指挥与控制学会 陈杰:关于C语言的,指向指针的指针,需要专业知识,懂的进。

来源:百度文库 编辑:神马品牌网 时间:2024/05/05 06:27:59
用指向指针的指针的方法对n个整数排序并输出。要求将排序单独写成一个函数。

整数和n在主函数中输入,最后在主函数中输出。

大家帮忙看看是哪儿出问题了,为什么结果不对?

#include <stdio.h>
void Sort(int **p, int times)
{
int *temp, i=0, j=0;
for (i=0; i<times-1; i++)
{
for (j=i+1; j<times; j++)
{
if (**(p+i) > **(p+j))
{
temp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = temp;
}
}
}
}
void main()
{
int *str[20], i=0, times=0;
printf("input times to opt:\n");
scanf("%d", ×);
printf("Please input the figures:\n");
for (i=0; i<20; i++)
{
str[i]=(int*)malloc(sizeof(int));
}
for (i=0 ; i<times; i++)
{
scanf("%d", str+i);
}
printf("\nthe result is :\n");
Sort(str, times);
for (i=0; i<times; i++)
{
printf("%-6d", str[i]);
}
for (i=0; i<20; i++)
{
free(str[i]);
str[i]=NULL;
}
system("pause");
}

不知道为什么,网页屏蔽了一些字符

×处应该是 “取times的地址”。

回zwb82008: **表示二维指针。程序编译和连接均无问题,也不多括号。不过还是谢谢你的热心~~

谢谢 橡皮 的详细讲解,我用的是学编程的基础编译器,TC2.0,功能很弱,什么警告也没有就顺利通过了。。。准备换编译器。。。-_-!

也谢谢你seuliu,不过最佳答案只能选一个,抱歉啊

如楼上说的三、四处确实有问题。
scanf("%d", str+i);应该改为scanf("%d", *(str+i));
scanf的第二个参数是指针类型,而str+i是指针的指针类型。*(str+i)才是指针类型。
printf("%-6d", str[i]);应该改为printf("%-6d", *(str[i]));
因为str[i]是一个指针,所以应该用*取值。
楼主你用什么编译器啊?我用gcc立刻发现这两个警告了。

#include <stdio.h>
#include <malloc.h>//修正一处
#include <stdlib.h>//修正二处
void Sort(int **p, int times)
{
int *temp, i=0, j=0;
for (i=0; i<times-1; i++)
{
for (j=i+1; j<times; j++)
{
if (**(p+i) > **(p+j))
{
temp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = temp;
}
}
}
}
void main()
{
int *str[20], i=0, times=0, n=0;
printf("input times to opt:\n");
scanf("%d", ×);
printf("Please input the figures:\n");
for (i=0; i<20; i++)
{
str[i]=(int*)calloc(1,sizeof(int));
}
for (i=0 ; i<times; i++)
{
scanf("%d", &str[i][0]);//修正三处
}
printf("\nthe result is :\n");
Sort(str, times);
for (i=0; i<times; i++)
{
printf("%d,", str[i][0]);//修正四处
}
for (i=0; i<20; i++)
{
free(str[i]);
str[i]=NULL;
}
system("pause");
}

void Sort(int **p, int times)
怎吗 两个“**”!!
for (i=0; i<times-1; i++)
{
把“{”去了