Originally Posted by
tabstop
As for question 1, you put the question directly after the answer -- use a for-loop to assign each kh->plist[i] to be NULL. Probably, you don't have to do that, since calloc will fill each of your kh->plist[i] with all-bits-zero, which is usually the same deal.
As to 2, you have to decide where to put the guy, then use malloc to give you a piece of memory, and assign the return value of malloc to kh->plist[appropriate_number].
tks for helping me, however, this is what I implemented for question 2.
I commented on the code below
Code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define KH_SUCCESS 0x00
#define EKH_MAX_PERSON_EXCEED 0x01
struct _KPerson {
char *name; // person name
int age; // person age
};
typedef struct _KPerson KPerson;
struct _KHome {
KPerson **plist; // pointer to pointer of struct array
int msize; // max size alloweed
int csize; // current size
};
typedef struct _KHome KHome;
KPerson* kperson_new(const char* _n, const int _a)
{
KPerson *kp;
kp = (KPerson *) calloc( 1, sizeof( KPerson ) );
kp->name = (char *) calloc( strlen(_n) + 1, sizeof( char ) );
strncpy( kp-> name, _n, strlen(_n) + 1 );
kp->age = _a;
return kp;
};
KHome* khome_new( const int _ms )
{
KHome *kh;
int i = 0;
kh = (KHome *) calloc( 1, sizeof( KHome ) );
kh->plist = (KPerson **) calloc( _ms, sizeof( KPerson * ) );
kh->msize = _ms;
kh->csize = 0;
return kh;
};
int khome_insert( KHome *kh, const KPerson* kp )
{
if( kh->csize >= kh->msize )
return EKH_MAX_PERSON_EXCEED;
/* ??? [1] - What's wrong with this part of code? */
kh->plist[kh->csize]->name = (char *) calloc( strlen( kp->name ) + 1, sizeof( char ) );
strncpy( kh->plist[kh->csize]->name, kp->name, strlen( kp->name ) + 1 );
/* ============================================== */
kh->plist[kh->csize]->age = kp->age;
++kh->csize;
return KH_SUCCESS;
};
int main( int argc, char **argv )
{
/* testing code here */
KHome *kh = khome_new(3);
KPerson *kp = kperson_new( "Pete Houston", 22 );
int res = khome_insert(kh, kp); // segmentation fault
if( res == KH_SUCCESS )
printf(" %s \n ", kh->plist[0]->name);
free( kh );
return 0;
}