Code:
int main()
{
char *name=NULL;
int n;
printf(\"\\nenter the string\\n\");
scanf(\"%s\",name);
n=strlen(name);
printf(\"%d\",n);
return 0;
}
You didn't allocate any memory for pointer to char name
.
Example:
char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;
Try this,
int main()
{
char *name = malloc(sizeof( char ) * LENGTH); // define LENGTH as you desired
int n;
printf("\nenter the string\n");
scanf("%s",name);
n=strlen(name);
printf("%d",n);
free(name);
}
Problem is you did not allocate memory for pointer. So allocate memory tp pointer with malloc(BUFSIZE)
. Also at the end you have to free your allocated memory with free(name)
.
C is not a managed language, so you need to tell your string (char *) wihch lenght of memory are you giving it. Here comes the malloc function.
By the way, there is no GarbageCollector, so you'll need to free your char * when you'll have finish to use it.
But be careful, malloc can return null, so your char * would be unable to store any char !
int main(int argc, char **argv)
{
char *name = null;
// Malloc your char *
if ((name = malloc(sizeof( char ) * LENGTH_OF_YOUR_LARGER_INPUT)) == null)
return;
int n;
printf("\nenter the string\n");
scanf("%s",name);
n=strlen(name);
printf("%d",n);
// Free the allocated memory to your char *
free(name);
}
Instead of char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;
USE
char * name = malloc(MAX_STRING_LENGTH+1 ); //+1 is to store Null character
and sizeof(char)==1
so you can avoid it.