【问题标题】:Cannot display all the element of my array in C?无法在 C 中显示我的数组的所有元素?
【发布时间】: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] &gt; tab[j+1]) 访问数组外部。需要限制所以j+1 &lt; taille

标签: arrays c sorting pointers display


【解决方案1】:
  1. 您不应使用5 硬编码数组的大小。相反,您应该使用sizeof(dtab)/sizeof(dtab[0])

  2. ordonnerTableau 内部,您有taille=5,但您尝试在以下位置获取tabtab[j] &gt; tab[j+1],但不确定jj+1 是否小于5。

【讨论】:

  • 它有效,兄弟们! :-)
  • @AndreasWenzel,完成了
猜你喜欢
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 2014-07-29
  • 2016-02-12
  • 1970-01-01
相关资源
最近更新 更多