Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Memory allocation 1

Status
Not open for further replies.

raghu75

Programmer
Nov 21, 2000
66
IN
All,
I have to allocate memory for the code as below..hou to do it...

char** a;

I need to store two strings in 'a',for which i need to allocate memory.Can anyone tell me.
 
Here's one way...

char** DoCharDoublePointer(char* lpString1,char* lpString2)
{
unsigned long len;
char** C;

len=strlen(lpString1);
C=(char**)malloc(sizeof(char**));
//create static pointer to char*

*C=(char*)malloc(len+strlen(lpString2)+2);
//allocate string space plus two termination zeros

strcpy(*C,string1);
//copy the first string

*C=*C+len+1;
//set the char* to point past the first string

strcpy(*C,lpString2);
//copy second string to char*

return C;
//return the char**, which points to the string
//pointer, not the string.
}

Some of the steps may be combined if you want too.
Good luck.

 
char** a;
int num_strings=1;
a=(char**)malloc(num_strings*sizeof(char*));
a[0]=(char*)malloc(strlen("hello word")+1);
a[1]=(char*)malloc(strlen("good bye")+1);
.....
free(a[0]);
free(a[1]);
free(a); John Fill
1c.bmp


ivfmd@mail.md
 
In John's example, he doesn't allocate quite enough memory, num_strings should be at least 2 to allow indexing to a[1].

Anyway, here's my example:

#include <stdlib.h>

/* ... */

#define STRING_SIZE 20

int num_strings=2;

char **a=malloc(num_strings * sizeof *a);
char s1[]=&quot;hello&quot;;
char s2[]=&quot;world&quot;;

if (a) {
a[0]=malloc(sizeof s1);
a[1]=malloc(sizeof s2);
if (a[0] && a[1]) {
strcpy(a[0],s1);
strcpy(a[1],s2);

/* ... */
free(a[0]);
free(a[1]);
}
free(a);
}


Russ
bobbitts@hotmail.com
 
My mistake. int num_strings=1; should be int num_strings=2; in my code. I've focused my attention on memory allocating.
By the way, sizeof s1 is not too reliable. For example if instead of char s1[] was char* s1 your sizeof would return always 4. John Fill
1c.bmp


ivfmd@mail.md
 
Right, but since I knew s1 was an array I used sizeof. Why waste processor time with strlen() when you can have the C preprocessor give you the same information for free? :)
Russ
bobbitts@hotmail.com
 
If you want to do like two dimensional array then

int main()
{
char (*a)[10];
a = (char (*)[10]) malloc(sizeof(20));
strcpy(a[0], &quot;012345678&quot;);
strcpy(a[1], &quot;123456789&quot;);
printf(&quot;\n %s %s&quot;, a[0], a[1]);
return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top