Ojaswe Gupta
Ojaswe Gupta

Reputation: 1

Declaring/using char pointer inside a struct in c and taking input in it

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

Answers (2)

Born Ready
Born Ready

Reputation: 3496

Dynamic memory allocation

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

Micha&#235;l Roy
Micha&#235;l Roy

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

Related Questions