2016-03-23 94 views
0

我意識到這個問題經常被問到,但我還是不太明白它是如何工作的。我想嘗試將我的文件讀入我的結構中,在函數內部並通過指向函數的指針傳遞結構。我不確定如何寫函數原型。使用指針傳遞結構體和返回數組的結構體和返回數組 - 功能

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

#define MAX 90 
#define STR 200 
#define MAXLEN 40 

struct human { 
    char name[MAXLEN]; 
    char surname[MAXLEN]; 
    int age; 
    float weight; 
}; 
int main(int argc, char *argv[]) { 
    char *dlim= " ", *end = "\n"; 
    char *string; 
    string = (char *)malloc(sizeof(char) * STR); 
    int i = 0, j = 0; 
    struct human *man = malloc(sizeof(struct human) * MAX); 

    FILE *fin = fopen("data.txt", "r"); 
    if (fin == NULL) { 
     printf("Cannot open file\n"); 
     exit(0); 
    } 
    while (fgets (string, STR, fin)){ 
     read (string, &man[i], dlim, end); 
     i++; 
    } 
    fclose(fin); 

    free(string); 
    free(man); 

    return 0; 
} 

struct human *man read(char *fstring, struct *man, char *div, char *end){ 
    int i=0; 
    char *tok; 

     tok = strtok(string, dlim); 
     strcpy(man[i].name, tok); 

     tok = strtok(NULL, dlim); 
     strcpy(man[i].surname,tok); 

     tok = strtok(NULL, dlim); 
     man[i].age = atoi(tok); 

     tok = strtok(NULL, end); 
     man[i].weight = atof(tok); 

    return man[i]; 

} 

這個功能是什麼意思?我是否正確地假設通過使用指針,該結構將自動更新在主,無需返回的東西在函數中?

函數也可以不返回任何東西(void),因爲指針的使用會自動傳遞給main?

謝謝!

+0

函數read必須返回一些東西。你不需要返回一個結構體的人類指針。你已經傳入了一個指向要填充的結構的指針。如果失敗,你最好返回0,如果成功或者返回一個非零的錯誤代碼。這是一個典型的行爲。 – bruceg

回答

2

您的代碼很接近,但填充人體結構的子例程中的指針邏輯不正確。看下面的返工和輕微的簡化,是否有助於你理解如何傳遞結構:

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

#define MAXIMUM_HUMANS 90 
#define MAXIMUM_INPUT_STRING_LENGTH 200 
#define MAXIMUM_STRING_LENGTH 40 

struct human { 
    char name[MAXIMUM_STRING_LENGTH]; 
    char surname[MAXIMUM_STRING_LENGTH]; 
    int age; 
    float weight; 
}; 

void initialize_human(char *string, struct human *man, char *delimiter, char *end) { 
    char *token; 

    token = strtok(string, delimiter); 
    strcpy(man->name, token); 

    token = strtok(NULL, delimiter); 
    strcpy(man->surname, token); 

    token = strtok(NULL, delimiter); 
    man->age = atoi(token); 

    token = strtok(NULL, end); 
    man->weight = atof(token); 
} 

int main(int argc, char *argv[]) { 
    char *dlim= " ", *end = "\n"; 
    char string[MAXIMUM_INPUT_STRING_LENGTH]; 
    struct human humans[MAXIMUM_HUMANS]; 

    FILE *fin = fopen("data.txt", "r"); 

    if (fin == NULL) { 
     fprintf(stderr, "Cannot open file\n"); 
     exit(1); 
    } 

    int population; // after loop, this contains total body count 

    for (population = 0; fgets(string, MAXIMUM_INPUT_STRING_LENGTH, fin); population ++) { 
     initialize_human(string, &humans[population], dlim, end); 
    } 

    printf("population: %d\n", population); 
    printf("last added: %s who weighs %f\n", humans[population - 1].surname, humans[population - 1].weight); // test if we loaded it up correctly 

    fclose(fin); 

    return 0; 
}