LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   malloc (https://www.linuxquestions.org/questions/programming-9/malloc-425128/)

anoosh 03-15-2006 03:20 PM

malloc
 
hi there.
I have these two structures below:
struct name{
char *firstn,*lastn;
};
typedef struct name NAME;
struct student{
NAME stname;
int *mark;
}*st;
typedef struct student STUDENT;
_________________________________________________________
I have 3 pointers:firstn,lastn and st and I'm going to use them as dynamic arrays.
please tell me how to allocate dynamic memory for that in C.

paulsm4 03-15-2006 04:41 PM

You answered your own question: you can "malloc()" each of the strings.

Stylistically, I'd lose the "typedefs".

If you really insisted on using typedef's, however, I'd *definitely* include them in your struct definition:
Code:

  /* POOR */
  struct name
  {
    char *firstn, *lastn;
  };
  typedef struct name NAME;
  ..
  NAME myName;

  /* BETTER */
  typedef struct name
  {
    char *firstn, *lastn;
  }
    name;
  ..
  name myName;


  /* BETTER STILL */
  #define MAXNAME 20
  struct name
  {
    char firstn[MAXNAME];
    char lastn[MAXNAME];
  };
  ..
  struct name myName;

And, if you're using C++:
Code:

  // BEST
  class Name
  {
    public:
      Name (const char *fname, const char *lname);
      char *getFirstName ();
      char *getLastName ();
    private:
      char firstn[MAXNAME], lastn[MAXNAME];
  };
  ..
  Name *myName = new Name ("Miles", "Standish");

PS:
If you're using C++, you might consider just using the Standard C++ "string" class. This eliminates the whole issue of what to "malloc()", when...


All times are GMT -5. The time now is 03:42 PM.