Simple C Question

Status
Not open for further replies.

Anton

Registered Member
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
 
/* 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:
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!
 
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!
 
Status
Not open for further replies.
Back
Top