Search code examples
cpointersstructdynamic-memory-allocation

C: How to modify the max size of a string in a struct?


The exercise gives a simple program to create databases, and this program turns around the following structure

struct Address {
  int id;
  int set;
  char name[MAX_DATA];
  char email[MAX_DATA];
};

I'm asked to modify the code so I can pass as an argument to the program the maximal length of .name and .email. Now, of course, if instead of defining MAX_DATA as a macro I work with it as a global variable, I get the error: variably modified 'name' at file scope.

Then I tried to create different if-loops aiming to pass the MAX_DATA value by redefiningstruct Address, for example:

if(argc > 6) {
  int maxdata = atoi(argv[6]);
  struct Address {
    int id;
    int set;
    char name[maxdata];
    char email[maxdata];
  };
  DatabaseSet(conn, id, argv[4], argv[5]);
  DatabaseWrite(conn);
  break;
}

but DatabaseSet and DatabaseWrite (which work on a struct Connection that relates to another struct Database, who finally relates directly to struct Address) ignore the new lengths of name and email.

EDIT: THANKS.

Thank you all for your comments and answers, your really helped me out with the exercise and with my general undestanding of C.


Solution

  •   struct Address {
        int id;
        int set;
        char *name;
        char *email;
      };
    

    Then allocate memory dynamically in name and email based on your MAXDATA input.

    Then you do this struct Address p.

    And

    p.name = malloc(MAXDATA);
    if( p.name == NULL ){
       fprintf(stderr,"%s\n","Error in memory allocation");
       exit(1);
    }
    

    and then when you are done working with it

    free(p.name);
    

    In case you allocate memory for email you will have to call free() on it the sane way as shown before.