0

我试图在整数数组中找到最小值。然后用具有该分数的人的姓名显示该值。我可以找到哪个值是最低的,并用像 player 1 或 player 2 这样的索引显示它,但我不能用名称代替那个索引。

#include <string.h>
#include <stdio.h>
#include <string.h>
#define LEN_NAME 34
#define NUM_NAMES 3
void lowest(int array[], char *fullName, int elements);
int main (void) {
    int scores[NUM_NAMES] = { 230,330,423};
    char firstName[NUM_NAMES][LEN_NAME] = {"john","james","mario"};
    char lastName[NUM_NAMES][LEN_NAME] = {"goirgi", "edison", "luca"};
    char *fullName[NUM_NAMES][LEN_NAME];
    int i;
    for (i=0; i < NUM_NAMES; i++) {
        strcpy(fullName[i], firstName[i]);
        strcat(fullName[i], " " );
        strcat(fullName[i], lastName[i]);
        printf("Your scores is %d with your full name is %s.\n",scores[i], fullName[i]);
    }

    lowest(scores,*fullName, NUM_NAMES);
    return 0;
}

void lowest (int array[], char *fullName, int elements) {
    int i,small = array[0], j;
    for (i=0; i< elements; i++) {
        if (array[i] < small) {
            small = array[i];
            j = i;
        }
    }
    printf("The lowest scored %d with score %d.\n", j , small);
}
4

3 回答 3

1

firstName、lastName 和 fullName 是被视为 (LEN_NAME x NUM_NAMES) 矩阵的连续内存区域。当您将它们传递给周围时,被调用函数需要知道行长度(LEN_NAME),以便当它通过i( fullName[i]) 下标时,它将进行计算fullName + (i * LEN_NAME)(这里 fullName 是内存区域的起始地址),以便它会到达第 i 个名字的开头。

#include <string.h>
#include <stdio.h>
#include <string.h>
#define LEN_NAME 34
#define NUM_NAMES 3
void lowest(int array[], char fullName[][LEN_NAME], int elements);
int main(void)
{
    int scores[NUM_NAMES] = { 230, 330, 423 };
    char firstName[NUM_NAMES][LEN_NAME] = { "john", "james", "mario" };
    char lastName[NUM_NAMES][LEN_NAME] = { "goirgi", "edison", "luca" };
    char fullName[NUM_NAMES][LEN_NAME];
    int i;
    for (i = 0; i < NUM_NAMES; i++) {
        strcpy(fullName[i], firstName[i]);
        strcat(fullName[i], " ");
        strcat(fullName[i], lastName[i]);
        printf("Your scores is %d with your full name is %s.\n", scores[i],
               fullName[i]);
    }

    lowest(scores, fullName, NUM_NAMES);
    return 0;
}

void lowest(int array[], char fullName[][LEN_NAME], int elements)
{
    int i, small = array[0], j = 0;
    for (i = 0; i < elements; i++) {
        if (array[i] < small) {
            small = array[i];
            j = i;
        }
    }
    printf("%s scored %d.\n", fullName[j], small);
}

在这种情况下,创建指向字符的指针数组通常更惯用:

char *fullName[NUM_NAMES];
fullName[0] = malloc(LEN_NAME);
// ...

您可以记住它们的长度或将NULL指针放在最后一个位置。如果你这样做,你需要声明lowest为:

void lowest(int array[], char *fullName[], int elements);
于 2013-06-25T18:36:32.037 回答
0

我认为这是一个错字:

char *fullName[NUM_NAMES][LEN_NAME];
     ^

在这里,您已经声明了一个二维指针数组,但您没有将它们指向任何东西。

于 2013-06-25T18:35:55.410 回答
0

一个简单的解决方案是传递一个数字数组和一个名称数组,并确保列表具有匹配的索引。一旦找到最低值的索引,您就可以简单地索引到名称列表中以显示该值。

于 2013-06-25T18:35:28.097 回答