如何在C编程中传递2d字符串数组?

时间:2013-06-25 18:29:41

标签: c string multidimensional-array

我试图找到整数数组中的最小值。然后使用具有该分数的人的姓名显示该值。我可以找到哪个值是最低的adn显示它与索引如播放器1或播放器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);
}

3 个答案:

答案 0 :(得分:1)

firstName,lastName和fullName是被视为(LEN_NAME x NUM_NAMES)矩阵的连续内存区域。当你传递它们时,被调用的函数需要知道行长度(LEN_NAME),这样当它ifullName[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);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我认为这是一个错字:

char *fullName[NUM_NAMES][LEN_NAME];
     ^

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