【发布时间】:2023-04-02 02:34:01
【问题描述】:
我的阵列有些问题。好吧,我想对一个包含 5 个整数元素的数组进行排序。但是,当我显示它们时,它只显示最后一个元素,并且它的值不是我期望的排序后的值。
因此,能帮我解决这个问题吗?
注意:这是我的代码
main.h
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.h
* Author: Yacin
*
* Created on 19 septembre 2021, 12:49
*/
#ifndef MAIN_H
#define MAIN_H
int sommeTableau(int tab[], int taille);
int moyenneTableau(int tab[], int taille);
int * copieTableau(int tab1[], int tab2[], int taille);
int * valMaxTableau(int tab[], int taille, int valMax);
int * ordonnerTableau(int tab[], int taille);
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* MAIN_H */
main.c - ordonnerTableau 函数:
int * ordonnerTableau(int tab[], int taille){
int tmp;
int i;
for (i = 0; i < taille; i++){
int j = 0;
while(tab[j] > tab[j+1]){
tmp = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tmp;
j++;
}
}
return tab;
}
main.c - 主要功能:
int main(int argc, char** argv) {
int dtab[5] = {12, 9, 2, 1, 0};
printf("Avant :\n");
for (int k = 0; k < 5; k++) {
printf("tab[%d]=%d\n",k , dtab[k]);
}
printf("\n");
printf("Après :\n");
for (int j = 0; j < 5; j++) {
printf("tab[%d]=%d \n",j ,*(ordonnerTableau(dtab, 5) + j));
}
输出:
Avant :
tab[0]=12
tab[1]=9
tab[2]=2
tab[3]=1
tab[4]=0
Après :
tab[4]=0
预期输出:
dtab[5] = {0,1,2,9,12}
任何帮助将不胜感激。
问候。
YT
【问题讨论】:
-
while(tab[j] > tab[j+1])访问数组外部。需要限制所以j+1 < taille。
标签: arrays c sorting pointers display