简体   繁体   中英

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);
}

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM