Reputation: 1
I am declaring a pointer to a character inside struct, and then taking input from user to store a string in that char pointer, but getting an error,please help
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct arr
{
char *str;
int len;
} s1;
int main()
{
scanf("%s", s1.str);
s1.len = strlen(s1.str);
printf("%d", s1.len);
}
Upvotes: 0
Views: 656
Reputation: 3496
In main function :
s1 *p = (s1 *)malloc(sizeof(s1));
if ( p == NULL )
{
printf("Memory allocation failed \n")
exit (0);
}
p->str = (char*)malloc(sizeof(char)*256); // here 256 bytes allocated
if (p->str)
{
printf("Memory allocation failed \n")
exit (0);
}
Then use :
free(p)
To free the memory previously allocated.
Upvotes: 0
Reputation: 6471
A char* is not enough to store a string, as a char* points to a string.
You need memory space to store the string itself.
Example:
struct arr
{
char str[128]; // will store strings up to 127 bytes long, plus the ending nul byte.
int len;
} s1;
int main()
{
scanf("%127s", s1.str);
s1.len = strlen(s1.str);
printf("%d", s1.len);
}
Upvotes: 1