Help answer threads with 0 replies.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 03-15-2006, 03:20 PM   #1
LQ Newbie
Registered: Aug 2004
Location: IRAN
Posts: 7

Rep: Reputation: 0

hi there.
I have these two structures below:
struct name{
char *firstn,*lastn;
typedef struct name NAME;
struct student{
NAME stname;
int *mark;
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.
Old 03-15-2006, 04:41 PM   #2
LQ Guru
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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:
  /* POOR */
  struct name
    char *firstn, *lastn;
  typedef struct name NAME;
  NAME myName;

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

  #define MAXNAME 20
  struct name
    char firstn[MAXNAME];
    char lastn[MAXNAME];
  struct name myName;
And, if you're using C++:
  // BEST
  class Name
      Name (const char *fname, const char *lname);
      char *getFirstName ();
      char *getLastName ();
      char firstn[MAXNAME], lastn[MAXNAME];
  Name *myName = new Name ("Miles", "Standish");
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...

Last edited by paulsm4; 03-15-2006 at 04:45 PM.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
malloc eagle683 Programming 6 05-22-2005 02:40 PM
problem using malloc in C huble Programming 10 03-27-2005 12:45 AM
malloc in c programming saiz66 Programming 18 10-04-2004 02:00 PM
malloc() vijeesh_ep Programming 4 08-25-2004 03:50 PM
about malloc eshwar_ind Programming 11 02-18-2004 03:41 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:21 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration