Recently I was working on some string related programs. I came across some error, when I asked my friend he also faced the same issue.
Even though it is very trivial, I came to know since we were away from some basics for long time, we faced this issue.
In C we don't have string type. So we basically use either
char *cb="name";
char c[5]="name";
Now the difference between two are cb is pointer to char array. and c is itself a array which has "name" stored in it.
More deeeply,
when we do *cb="name";
In C memory layout --->data segment--->initialized data segment "name" is stored and cb is stored either in heap,stack,data segment depending on local,static,extern variable.
And it stored value of "name". Also the address where name is stored is READ ONLY.
So you cannot do cb[2]='g';
Now using cb, we can perform strcmp function or other function which will use the string stored at cb pointer.
But if we want to do strcpy , then error will be thrown. Simply because we haven't MALLOCed anything.
So what about the below functions. Working below two functions will tell more difference
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *t;
t= (char *)malloc(sizeof(char)*7);
t="chetan";
printf("%s",t);
strcpy(t,"rathore");
printf("%s",t);
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *t;
t= (char *)malloc(sizeof(char)*7);
strcpy(t,"rathore");
printf("%s",t);
t="chetan";
printf("%s",t);
return 0;
}
The below program will further give some insight
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *t;
t= (char *)malloc(sizeof(char)*7);
strcpy(t,"rathore");
printf("%s",t);
t="chetan";
printf("%s",t);
free(t);
return 0;
}
Now when we use
char cb[5]="name";
here cb is allocated space in heap or stack depending on local,static,extern.
so we can perform cb[3]="k"
also all strcmp and strcpy will work. But what will not work here is
cb=NULL, since cb is not pointer.
cb='\0'; since cb is not pointer
BOTH WILL GIVE COMPILE TIME ERROR
Also strcpy(cb,NULL) or strcpy(cb,'\0') will give RUNTIME ERROR
Please pay attention to COMPILE ERROR and RUNTIME and LINK TIME ERROR.
Below program will tell difference between pointer of any type and array of same type.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int t[4];
int *a;
t=&a;
}
At the closing stages , some more points .
In case you have defined array char
char strin[6];
then to make string empty , we can use strcpy(strin,"");
but in case we have char pointer , we could have used
char *strin;
strin=NULL; or strin='\0';
No comments:
Post a Comment