Simple C Question

Discussion in 'Computer Science & Culture' started by Anton, Mar 27, 2002.

Thread Status:
Not open for further replies.
  1. Anton Registered Member

    Messages:
    8
    Forum Members,

    Now before any recommendations to use C++ I realize this would be a lot easier with C++, but the project was already started by other members in my group. I realize this is a silly question and I can't understand why I don't know it.

    I need to know how to dynamically create an array of strings size 50 characters. I know how many in the array i need, its stored in int n. So how would i use malloc() or calloc() to do this? Any help please.

    -Anton
     
  2. Google AdSense Guest Advertisement



    to hide all adverts.
  3. Adam §Þ@ç€ MØnk€¥ Registered Senior Member

    Messages:
    7,415
    /* declarations */
    char *StringPointer;
    void *malloc(unsigned);

    /*initialisation when/where needed */
    StringPointer = (char *)malloc(strlen(str)+1);

    Something like that. Can't recall exactly, sorry. The malloc of strlen()+1 gives you the string size of the passed string (str) plus the end of string terminator.
     
    Last edited: Mar 27, 2002
  4. Google AdSense Guest Advertisement



    to hide all adverts.
  5. Rick Valued Senior Member

    Messages:
    3,336
    You are certainly not using Turbo C compiler,had it been you wouldnt have asked this...

    why would you first declare malloc?

    lets say you wanna allocate dynamically,in case of linked list.
    say... do this.


    struct node
    {
    int data;
    struct node *next;
    };
    typedef struct node a;
    a *fresh;
    a *start;
    ...blah...blah...

    //this is the thing.

    fresh=(a *)malloc(sizeof(a));
    in case of calloc you have to specify the number of bytes.like if you allocate something for integer,you"ll have to pass 2 to it...



    bye!
     
  6. Google AdSense Guest Advertisement



    to hide all adverts.
  7. Rick Valued Senior Member

    Messages:
    3,336
    in case you wanna print some names of say 100 students etc,(at the time of execution only i mean,since the memory is allocated whatever is required)just put the limit...


    bye!
     
Thread Status:
Not open for further replies.

Share This Page