2015-02-06 79 views
0

我正在研究一個簡單的「電話索引」項目。 我的項目是做出來的:結構,數組,指針如何通過指向這些結構的指針數組訪問結構的成員

if've:

索引來定義人的結構:

和三個函數來創建用戶,將它們添加到索引,顯示指數:

這裏是我的代碼:

// This is my structure definition 

typedef struct 
{ 
    char fname[30]; 
    char lname[30]; 
    char phnum[14]; 

} PERS; 

// Function prototypes 

PERS * add_person(void); 
PERS ** add_index(int); 
void show_index(PERS **, int); 

// Function implementation 

PERS * add_person(void) 
{ 
    PERS * p = (PERS *) calloc(1,sizeof(PERS)); // Dynamic allocation. 
    printf(" First name : "); 
    scanf("%s", p->fname); 
    printf(" Last name : "); 
    scanf("%s", p->lname); 
    printf(" Phone number : "); 
    scanf("%s", p->phnum); 

    return p; // return a pointer to the structure PERS 
} 


PERS ** add_index(int nbr) 
{ 
    int i = 0; 
    PERS * r[nbr]; // an array of pointers to PERS structures. 

    while(i < nbr) 
    { 
     r[i] = add_person(); // populate the array with pointers to PERS 
     i++; 
     printf("\n"); 
    } 

    return r; // return the array 
} 


void show_index(PERS **rep, int nbr) // recieve the array 
{ 
    int i = 0; 

    while(i < nbr) 
    { // display its content 
     printf("\n"); 
     printf(" %s \n", rep[i]->fname); 
     printf(" %s \n", rep[i]->lname); 
     printf(" %s \n", rep[i]->phnum); 
     i++; 
    } 
} 

當然主程序:

#include <stdio.h> 
#include <stdlib.h> 
#include "funcs.h" 

int main() 
{ 
    PERS ** rep = add_index(3); // Create an index with three items 

    printf("\n\n"); 

    show_index(rep,3); 

    printf("\n\n"); 

    return 0; 
} 

這是我輸入:

First name : friend 
Last name : name 
Phone number : 4567234512 

這是錯誤我得到:

(null) 
Segmentation fault (core dumped) 

我已經嘗試了幾種解決方案,但它不工作。

在此先感謝。

+3

你在'add_index返回一個指針到本地陣列()':'r'是本地所以'回報R等'使它超出範圍。使用它產生的指針是未定義的行爲。您還需要動態內存分配。順便說一下,您獲取用戶輸入的方法非常危險。不要使用'scanf()';總是更喜歡'fgets()'(它更容易避免緩衝區溢出錯誤)。 – 2015-02-06 15:15:21

回答

1

你知道嗎?你可以通過改變一行來解決你的問題。

PERS **r= malloc(sizeof(PERS *) * nbr); 

使用指針,指針和從函數返回這個值..

+0

@JohnBollinger我等你看看它:) – Gopi 2015-02-06 16:18:45

+0

結構的存儲已經保留在'add_person()' 和指向這個存儲的指針存儲在 'add_index()'中的指針數組中,該數組的地址將返回並存儲在主程序中的一個 雙指針中。 我想要的是通過主程序中的指針來訪問這些成員,所以我把它傳遞給函數'show_array()'這樣的訪問它: index [i] - > member。 – c0d3r 2015-02-06 18:51:10

+0

我已經工作了,我得到了一些結果,但不是我想要的: 我做了太多成員的索引,我把指針指向'show_index()',這就是我得到的結果: first :0x1aada8 = 1748392 第二:0x794fc381 = 2035270529 第一個: 名:FRIEND1 二名:TEST1 電話號碼:45 第二: 名:FRIEND2 二名:TEST2 電話號碼:78 out放: 朋友1 test1的 垃圾 垃圾 垃圾 – c0d3r 2015-02-06 19:37:16