Reputation: 1235
I am a novice in C and trying to understand basic concepts in C, Like when and Why I have to allocate Memory for a string pointer. here I have a sample program. I have commented in appropriate locations. Please help me understand.
/ Please help me understand why do I have allocate Memory in Case 2 while I don't have to in Case 1.
#include<stdio.h>
void xcopy(char *t,const char *s);
int main(int argc, char const *argv[])
{
char name1[]="Asfakul";
char *name;
char *target;
name=name1; // Here I dont have to allocate Memory (Case 1)
puts(name);
target=(char*)calloc(10,sizeof(char)); // Here I have to allocate Memory (Case 2)
xcopy(target,name);
return 0;
}
void xcopy(char *t,const char *s)
{
while( *s !='\0')
{
*t=*s;
t++;
s++;
}
puts(t);
}
Upvotes: 0
Views: 61
Reputation: 223699
In the first case, you start with name1
, which is an array of char
. Then you take name
, which is a char *
, and assign name1
to it. Since name1
is being evaluated in pointer context, it refers to a pointer to the first element of the array. So now name
points to the first element of name1
.
In the second case, target
is assigned a memory location returned by a call to calloc
, which in this case is a block of 10 bytes. The bytes now pointed to by target
can now be used.
As with any pointer, you need to assign it a value before you can dereference it. That value can be either the address of some other variable, or a block of memory returned by the malloc
family of functions.
Upvotes: 1
Reputation: 16607
name=name1; // Here I dont have to allocate Memory (Case 1)
In this case , you don't allocate memory to name
, you just make it point to array name1
. In short , name
now has address of first element of array name1
.
target=(char*)calloc(10,sizeof(char)); // Here I have to allocate Memory (Case 2)
xcopy(target,name);
And in case 2
you need to allocate memory as you copy the contents of name1
at the memory block to which target
points to .
Here , it is needed as if you don't allocate memory then target
point to anything (maybe garbage) and writing to that location will cause undefined behaviour.
Note - You don't need to free
any memory in case 1
as pointer points to a array on stack . But you need to do free(target);
in case 2
as you allocate memory on heap.
Upvotes: 1