TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Simon Avery
from: George White
date: 1998-08-07 10:05:00
subject: Dynamic Structs?

Hi Simon,

You asked:

SA>, , what are we going to do with you?

I don't know?

SA>Say I've got a struct, say;

SA>typedef struct CONFIGURATION
SA>        {
SA>        // chars and ints and stuff and botherment.
SA>        } CONFIG;

SA>Now, to use one of these, simple enough:

SA>CONFIG c;

SA>But, how do I create a variable number of structs, allocating the
SA>memory when needed.

Easy Peasy :-). You'll kick yourself when you see how easy!

SA>int num_of_configs=atoi(argv[1]);        // for example

SA>// Mystery Code here please. :)

/* Test Code */

/* As always, no warranty given, no guarantee as to the effect */
/* on your cat, marriage etc... */

#include 
#include 
#include 

typedef struct
    {
    char        name[26];
    char        node[26];
    } CONFIG;

int main (int argc, char *argv[])
{
int num_of_configs;
int counter;

CONFIG  *config_array;

if (argc > 1)
  num_of_configs = atoi(argv[1]);        /* for example */

if (NULL == (config_array = calloc (sizeof (CONFIG),num_of_configs)))
  return EXIT_FAILURE;  /* You can sort out better error handling */

/* Put some data in the array */
strcpy (config_array[0].name,"Simon Avery");
strcpy (config_array[0].node,"2:255/90");
strcpy (config_array[1].name,"George White");
strcpy (config_array[1].node,"2:440/4");
strcpy (config_array[num_of_configs - 1].name,"Last Entry");
strcpy (config_array[num_of_configs - 1].node,"No Node Listed");

/* And prove that it's there */
for (counter = 0;counter < num_of_configs;counter++)
    printf ("Struct %2d = '%s', '%s'\n",counter,
            config_array[counter].name,
            config_array[counter].node);

return EXIT_SUCCESS;
}

/* Emd of test code */

George

 * SLMR 2.1a * Computers eliminate spare time.

--- Maximus/2 3.01
* Origin: DoNoR/2,Woking UK (44-1483-717904) (2:440/4)
SEEN-BY: 396/1 622/419 632/371 633/260 267 270 371 634/397 635/506 728 810
SEEN-BY: 639/252 670/213 218
@PATH: 440/4 255/1 440/1 80 252/356 140/1 270/101 396/1 633/260 635/506 728
@PATH: 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.