我不知道該如何解釋這一點,但這段代碼的波紋管可以完全編譯,但是當你運行它,SIGSEV。 請問,有誰可以確切地知道我錯了什麼地方? 事實是我希望能夠訪問由如下指標,並在同一時間元素能夠與結構的工作。指向指向頭痛的struct的指針。 。
#include <stdio.h>
#include <stdlib.h>
/* This is a struct describing properties of an element */
struct element{
int age;
char* name;
};
/* This struct contains a pointer to a pointer on a element "struct element" */
struct person{
struct element** p;
int id;
};
/* Thus function initializes a struct person by allocation memory for it */
struct person* init(int size)
{
struct person* sample = (struct person*)malloc(size*sizeof(struct person));
sample->p = NULL;
sample->id = 0;
return sample;
}
/* use this function to insert a new element in the struct */
void insert(struct person* sample, char* _name, int _age)
{
sample->p[sample->id]->name = _name; /* the program crashes here according to the debugger , but why?? */
sample->p[sample->id]->age = _age; /* of course, this will cause trouble too because it has the same construct as the previous one */
sample->id++;
}
/* main entry */
int main()
{
struct person* student = init(10); /* Allocating space for 10 students */
insert(student, "kido", 8);
printf("Your name is %s and your age is %d", student->p[0]->name, student->p[0]->age); /* we can't write student->p->name */
return 0;
}
「誰能告訴正是」 調試器。 – 2011-03-22 17:32:57
@Piotr:在代碼中看到註釋:「程序根據調試器在這裏進行分割,但是爲什麼?」此外,+1包括完整的代碼。 – nmichaels 2011-03-22 17:36:39
@nmichaels:啊,那我就是盲目的。抱歉。 – 2011-03-22 17:41:51