2013-06-25 36 views
0

我想找到整數數組中的最小值。然後用具有該分數的人的姓名顯示該值。我可以找到哪個值是最低和最高值,像播放器1或播放器2一樣顯示索引,但我不能將名稱而不是該索引。如何在C編程中傳遞2d字符串數組?

#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); 
} 
+1

你試過'fullName [j]'? – SheetJS

回答

1

firstName,lastName和fullName是連續的內存區域,可視爲(LEN_NAME x NUM_NAMES)個矩陣。當你傳遞它們時,被調用函數需要知道行長度(LEN_NAME),以便當它通過ifullName[i])下標時,它將執行計算fullName + (i * LEN_NAME)(這裏fullName是存儲區開始的地址),以便它將達到我的名字的開頭。

#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); 
+0

謝謝,這工作:) – user2512806

0

一個簡單的解決方案是傳遞一個數組和一個名稱數組,並確保列表具有匹配的索引。一旦找到最低值的索引,就可以簡單地索引到名稱列表中以顯示該索引。

0

我覺得這是一個錯字:

char *fullName[NUM_NAMES][LEN_NAME]; 
    ^

這裏你聲明指針的二維數組,但是你有沒有指出他們任何東西。

相關問題