Originally Posted by
Adak
@Click_here: For a program of any importance, yes, you should free the memory you allocate.
@shruthi: You CAN save memory by using 2D (pointer to pointer) arrays, just like you were thinking about. It's just not "automatic", like the pre-defined strings you show: "mon", "tuesday", "wednesday". Each string needs to have it's length known, and the memory allocated for it. This would be a better program, (and a useful example), so it would be VERY worthwhile to free any allocated memory.
If you are ready to study and or practice using char pointers, it's a very worthwhile skill to learn how it works.
Ok,Ive given it a try.
Code:
#include#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str1[3];
char data[40];
int len;
fgets(data,sizeof(data),stdin);
fputs(data,stdout);
len=strlen(data);printf("length of the string=%d\n",len);
str1[0]=malloc(strlen(data));
strncpy(str1[0],data,len);printf("%s\n",str1[0]);
free(str1[0]);
return 0;
}
Able to take the input,find out it's length,create a memory of that size & copy the data into that,but the only thing is not able to place the null character after copying.