簡體   English   中英

分割錯誤,結構數組

[英]Segmentation Fault, Array of structures

我在構建結構數組時遇到了分段錯誤的麻煩。 早些時候,我有一個程序,該程序的計數器不正確,並一直出現分段錯誤,但我能夠修復它。 但是,使用此程序,我似乎無法弄清為什么它會繼續出現分段錯誤。 來自正在讀取的文件的輸入是

Anthony,Huerta,24
Troy,Bradley,56
Edward,stokely,23

我想讀取此文件,對其進行標記,獲取每個令牌並將其存儲在結構數組內部的自己的結構中,以便最后我可以像在數組中那樣打印結構的每個元素。 例如,我希望array [0]成為具有名字,姓氏和年齡的結構,這是我的代碼

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

struct info {
    char first[20];
    char last[20];
    int age;
};

int tokenize(struct info array[],FILE* in);

int main()
{
    struct info struct_array[100];
    FILE* fp = fopen("t2q5.csv","r");
    int size = tokenize(struct_array,fp);
    int z;
    for(z=0; z < size; z++)
        printf("%s %s %d",struct_array[z].first,struct_array[z].last,struct_array[z].age);
}

int tokenize(struct info array[],FILE* in)
{
    char buffer[20];
    char* token;
    char* first_name;
    char* last_name;
    char* age;
    char* del = ",";
    int number,count,index = 0; 

    while(fgets(buffer,sizeof(buffer),in) != NULL)
    {
        token = strtok(buffer,del);
        first_name = token;
        count = 1;
        while(token != NULL)
        {
            token = strtok(NULL,del);
            if(count = 1)
                last_name = token;
            if(count = 2)
                age = token;
            count = count + 1;
        }
        number = atoi(age);
        strcpy(array[index].first,first_name);
        strcpy(array[index].last,last_name);
        array[index].age = number;
        index = index + 1;
    }
    return index;
}

抱歉,如果它是一個小錯誤,我會很想念他們,但是我嘗試查找索引問題或類似問題,但我似乎無法發現它

執行相等性檢查時會發生錯誤。 if(count = 1)應該是if(count == 1)並且類似地對於count = 2 請記住, =用於分配,而==用於比較。

if(count = 1)if(count = 2) ,使用=運算符代替==運算符。 在這里,條件if(count = 1)if(count = 2)始終都始終為true。 由於其試圖分配1到變量count2至變量count分別。 然后最后這兩個if條件分別類似於if(1)if(2) if語句對所有非零值都為TRUE一樣,條件都變為true並始終執行。

為了避免此類編碼錯誤,請始終在邏輯相等的情況下將左側的常量保持不變,將右側的變量保持不變,例如if(1 == count) 如果不能正確地使用=這將給編譯錯誤。

暫無
暫無

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

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