我正在研究一个简单的“电话索引”项目。 我的项目是做出来的:结构,数组,指针如何通过指向这些结构的指针数组访问结构的成员
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)
我已经尝试了几种解决方案,但它不工作。
在此先感谢。
你在'add_index返回一个指针到本地阵列()':'r'是本地所以'回报R等'使它超出范围。使用它产生的指针是未定义的行为。您还需要动态内存分配。顺便说一下,您获取用户输入的方法非常危险。不要使用'scanf()';总是更喜欢'fgets()'(它更容易避免缓冲区溢出错误)。 – 2015-02-06 15:15:21