/*dynamically allocating memory in called funcion and freeing in caller*/
char** memall(int ns);
#define Max 20
#include<stdio.h>
int main()
{
char **s;
int i,ns;
printf("no of string you want to store");
scanf("%d",&ns);
s=memall(ns);
for(i=0;i<ns;i++)
printf("addrs =%u and string=%s\n",(s+i),s[i]);
for(i=0;i<ns;i++)
free(s[i]);
free(s);
/* s=NULL;
for(i=0;i<ns;i++)
printf("%s\n",s[i]);
*///dont try to access after freeing.
}
char** memall(int ns)
{
char **p;
char temp[100];
int i, j;
int c;
p=(char **)malloc(ns*sizeof(char *));
for(i=0;i<ns;i++)
printf("%u\n",p+i);
for(i=0;i<ns;i++)
{
j=0;
printf("\nenter the string %d",i+1);
while((c=getchar())=='\n'||c==' '||c=='\t');
temp[j++]=c;
while((c=getchar())!='\n')
temp[j++]=c;
temp[j] = '\0';
p[i]=(char *)malloc(strlen(temp) + 1);
printf("%u\n",p[i]);
strcpy(p[i],temp);
}
return p;
}
OUT PUT:
[Shark@localhost Dyns]$ gcc daarrof_chrptrs_nl.c
[Shark@localhost Dyns]$ ./a.out
no of string you want to store6
155586568
155586572
155586576
155586580
155586584
155586588enter the string 1Tom Gunn
155586600
enter the string 2Aia
155586616
enter the string 3Narue
155586632
enter the string 4Ancient Dragon
155586648
enter the string 5Yellow Snow
155586672
enter the string 6C surfer
155586688addrs =155586568 and string=Tom Gunn
addrs =155586572 and string=Aia
addrs =155586576 and string=Narue
addrs =155586580 and string=Ancient Dragon
addrs =155586584 and string=Yellow Snow
addrs =155586588 and string=C surfer
if we observe the out put the malloc in the loop at line 44 its allocating the memory with a 16 byte difference in its previous allocation and next allocation.
is there any reason underlying for so.
my secong question is
if i need a pointer to an array that increments the no of locations that is known at run time, how can i create it.
#define NOC 4
int (*ptr)[NOC] ;
ptr = ( int (*) [NOC] ) malloc ( 1024 );
here NOC is known at complile time but i want to decide at runtime.