0

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);
}
2
  • 5
    what error do you get? str is just a pointer, you need to allocate memory if you want to store a string Commented Apr 27, 2020 at 16:27
  • actually i need to take some input from user without knowing the length and use struct too, is there any way to do it. thanks Commented Apr 27, 2020 at 16:32

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

ya, but i dont know the length of the input array, is there any way to do it, i cant even use malloc function, doing question for a college assignment. thanks
That's a limitation of the language. You must allocate enough space for the longest string you expect to get, or need. For strings that could be very long, you provide a large buffer, then copy the string into a properly sized buffer allocated using malloc to avoid wasting too much memory space... The example above is the only way to do it without using malloc. It keeps the data within your structure, which is what you want.
Glad to be of help. :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.