Returning an Array of PointersCode examples of manipulating an array of pointers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLIST 10
struct ipList
{
int id;
char *name;
char *ip;
};
struct ipList **getList( void );
void printList( struct ipList **list );
int main( void )
{
struct ipList **theList;
theList = getList( );
printList( theList );
return 0;
}
struct ipList **getList( void )
{
struct ipList **list;
int i;
list = malloc( MAXLIST * sizeof( struct ipList * ) );
i = 0;
while ( i < MAXLIST )
{
list[ i ] = malloc( sizeof( struct ipList ) );
list[ i ]->id = i;
list[ i ]->name = "citibank.co.cx";
list[ i ]->ip = "209.249.147.15";
i++;
}
return ( list );
}
void printList( struct ipList **list )
{
int i = 0;
while ( i < MAXLIST )
{
printf( "%s - %s", ( list[ i ]->name ), ( list[ i ]->ip ) );
i++;
}
}
we can change the function getList slightly:
struct ipList **getList( void )
{
static struct ipList *list[ MAXLIST ];
int i;
//list = malloc( MAXLIST * sizeof( struct ipList * ) );
i = 0;
while ( i < MAXLIST )
{
list[ i ] = malloc( sizeof( struct ipList ) );
list[ i ]->id = i;
list[ i ]->name = "citibank.co.cx";
list[ i ]->ip = "209.249.147.15";
i++;
}
return ( list );
}
or we could have the main array created in main like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLIST 10
struct ipList
{
int id;
char name[ 35 ];
char ip[ 15 ];
};
void getList( struct ipList *list[ ] );
struct ipList *makeIP( void );
void printList( struct ipList *list[ ] );
int main( void )
{
struct ipList *theList[ MAXLIST ];
getList( theList );
printList( theList );
return 0;
}
void getList( struct ipList *list[ ] )
{
int i = 0;
while ( i < MAXLIST )
{
list[ i ] = makeIP( );
list[ i ]->id = i;
strcpy( ( list[ i ]->name ), "citibank.co.cx" );
strcpy( ( list[ i ]->ip ), "209.249.147.15" );
i++;
}
}
struct ipList *makeIP( void )
{
struct ipList *temp;
temp = malloc( sizeof( struct ipList ) );
return ( temp );
}
void printList( struct ipList *list[ ] )
{
int i = 0;
while ( i < MAXLIST )
{
printf( "%s - %s", ( list[ i ]->name ), ( list[ i ]->ip ) );
i++;
}
}
|
airships america attention batteries blogs books browser c++ computers copyright CSharp dharh disaster DIY DRM drugs economy energy environment FCC gaming government history HTML humor idt internet interview java javascript linkjack linux MLP moving music nature neThing neTodo networking news opensource philosophy podcasts politics poverty programming projects radio religion science sick simple software space sparce tagging technology twitter unbirthday video wiki
|

- a little order in the chaos where the mind dwells



