Link to home
Start Free TrialLog in
Avatar of Thunder_scream
Thunder_scream

asked on

dynamic string

I have a  code like this

typedef struct node {
    char str2[50];       // i dont want to allocate fixed array for my string
    struct node *next;
}NODE;


since I dont like to have the fixed array in my struct I have tried to create a dynmics string fn

char *new_string (char *src, int len)
{
    char *alloc;
    alloc = malloc (len+1);
    strncpy (alloc, src, 2);
    alloc[2] = 0;
    return (alloc);
}

but this is not a good solution as one must know the length of the string in before hand, and must remember to deallocate/free memory for the function.
The string is given through command line and the user shouldn't bother about how long the string is etc.

so the question is how do we create a dynamic string?
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi Thunder_scream,

> but this is not a good solution as one must know the length of the
> string in before hand,
No you dont have to know the string length ... neither malloc nor strncpy require you to know the length ...
strncpy (alloc, src, len);
alloc[len]=0;
would serve you just as well ...

Check return value from malloc, it can return NULL ...
alloc is also a function to allocate memory ... suggested to use a different name for the variable to avoid confusions

>and must remember to deallocate/free memory for
> the function.
this you must ... but that would be part of code that deletes node or entire list ... should not be a problem

> The string is given through command line and the user shouldn't bother
> about how long the string is etc.
User still does not have to know the length or bother about it
 
> so the question is how do we create a dynamic string?
Does the above satisfy your requirements or is there something else too ?

Cheers!
Sunnycoder
ASKER CERTIFIED SOLUTION
Avatar of F. Dominicus
F. Dominicus
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial