簡體   English   中英

C結構,具有結構功能

[英]Struct in C, functions with structs

我有此功能,並且我試圖在結構中的數組中搜索。 現在我無法理解我的錯誤在哪里,但是我認為那是在定義函數的那一部分,我嘗試將播放器的國家/地區轉換為小寫字母(在文件中包含國家/地區名稱)。 當我運行該程序並輸入國家/地區名稱時,在輸入要搜索的名稱后,該程序就會停止並崩潰。

有人可以幫助我嗎? 謝謝 。

#define NAME_LENGTH 50
#define NUM_PLAYERS 200

struct player_champ
{
    char player_country[NAME_LENGTH];
};

int search_player_by_country( struct player_champ  ptr_player[] , char asked_name[NAME_LENGTH], int lines_got);   
int main (void)    
{
    struct player_champ  player_info[NUM_PLAYERS] = { { 0 } };
    char asked_country[NAME_LENGTH]= {0};

    fflush(stdin);
    printf("\nEnter the name of the country you want to search for.\n\n>>>");
    fgets(asked_country, sizeof(asked_country)-1, stdin);
    asked_country[strlen(asked_country)-1] = '\0';
    search_player_by_country ( player_info, asked_country, num_lines_read);

    int search_player_by_country( struct player_champ ptr_player[] , char asked_country[NAME_LENGTH], int lines_got)
    {
        char temp_asked_country[NAME_LENGTH], temp_country_name[NAME_LENGTH];
        int i,k,z=0,j,counter=0;

        // there is a part of the code here that converts what user entered to lower case as well.

        for (i = 0 ; i < lines_got; i ++)
        {     
            k=0;

            /* while (ptr_player[i].player_country)
            {
                temp_country_name[j] = tolower (ptr_player.player_country);
                j++;
            }*/

            for (k = 0 ; k < lines_got; k ++)
            {
               temp_country_name[k] = tolower (ptr_player[k].player_country);
               k++;
            }
            temp_country_name[k] = '\0';

            if (strstr(temp_country_name, temp_asked_country) != NULL)
            {
               print_info( ptr_player[i]);
            }
        }
    }

這段代碼是完全錯誤的:

    for (k = 0 ; k < lines_got; k ++)
    {
        temp_country_name[k] = tolower (ptr_player[k].player_country);
        k++;
    }
  1. 您要在循環標題和正文中將k遞增兩次。
  2. 分配的目標是temp_country_name字符串中的單個字符,但是tolower()的參數是整個字符串。 您不是從編譯器收到警告,說tolower()的參數是錯誤的類型(它期望使用char ,您給它的是char* )嗎?
  3. 您已經在使用i遍歷外部循環中的行。 此循環應僅遍歷字符。

嘗試這個:

    for (k = 0 ; ptr_player[i].player_country[k]; k ++)
    {
        temp_country_name[k] = tolower (ptr_player[i].player_country[k]);
    }

ptr_player[i]是數組中元素i的播放器。 player_country[k]是該字符串中的字符k 因此ptr_player[i].player_country[k]是第i個玩家所在國家/地區的第k個字符。

您的代碼中可能還有其他問題,我沒有嘗試找到它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM