为什么我不能正确地将这个字符串数组分成更小的组?

问题描述 投票:0回答:1

我是 C 编程的初学者,仍然对数组感到困惑。我正在尝试创建一个程序,其中 42 个名称(按字母顺序排列)的数组被分为 7 个组,每个组有 5 个成员。棘手的部分是它的顺序。第一组由第一成员、最后一个成员、第二个成员、倒数第二个成员和第三个成员组成。基本上它在第一个和最后一个之间交替。

这是我迄今为止尝试过的:

#include <stdio.h>
#include <string.h>

int main() {
    const char students[42][50] = {"Alde", "Amio", "Ande", "Ayuson", "Bacabac", "Bisares", "Caparuzo", "Castro", "Dela Cruz", "Devera", "Frias", "Gailo", "Galvez", "Gamboa", "Geronimo", "Gutierrez", "Hernandez", "Landoy", "Lasay", "Lopez", "Luna", "Manalang", "Maranguis", "Matro", "Mercado", "Millonte", "Morshed", "Naz", "Neri", "Ogbac", "Oredina", "Pardillo", "Pedido", "Perez", "Piedad", "Rodriguez", "Santos", "Sañosa", "Takeuchi", "Uy", "Ventura", "Villavicencio"};
    int numberOfStudents = sizeof(students) / sizeof(students[0]);
    int j = numberOfStudents - 1;
    int numberOfGroups = 7;
    int groupSize = 5;
    char group[7][5][50] = {};
    int m = 0;

    for (int l = 0; l < numberOfGroups; l++) {
        int x = 0;  // Reset x for each group
        for (int i = 0; i < groupSize; i++) {
            if (j >= 0) {
                strcpy(group[l][x], students[m]);  // Use m for the first student
                x++;
                strcpy(group[l][x], students[j]);  // Use j for the second student
                x++;
                j--;
                m++;
            }
        }
    }

    // Print the groups
    for (int y = 0; y < numberOfGroups; y++) {
        printf("Group %d:\n", y + 1);
        for (int k = 0; k < groupSize; k++) {
            printf("\t%s\n", group[y][k]);
        }
        printf("\n");
    }

    return 0;
}

第一组是正确的,但我完全不明白为什么其他组中有跳过的名称和重复的名称。

arrays c multidimensional-array
1个回答
0
投票

在循环中

for (int i = 0; i < groupSize; i++)
,您将 x 的值增加两次。这意味着您将其值增加
groupSize * 2
倍,并且在几次迭代后它将变得越界。

– 一些程序员老兄

© www.soinside.com 2019 - 2024. All rights reserved.