How do I store a string of undefined length in a structure?

Question:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct Ecoponto{
   int codigo;
   int contentores[3];
   char cidade[20];
   char *rua;
   int nporta;
};


int main(int argc, char** argv) {

   struct Ecoponto ecoponto;
   printf("\nIntroduza o nome da rua:");
   scanf("%s",ecoponto.rua);
   printf("%s",&ecoponto.rua);



   return (EXIT_SUCCESS);
}

I would like to know the best way to store "the name of the street" with an unknown size in the "Ecoponto ecoponto" structure.

Answer:

To store a string of unknown length, without wasting extra memory, you need to read the street name into a buffer, a very large variable that can support any street name, for example, length 1000. Then use the string.hea library. strlen() function, which returns how many characters are in a string and use strlen(buffer).

Now you know how many characters are in the street name if you do

char buffer[1000]; 
scanf("%s", buffer);
int a = strlen(buffer);

You will be able to use the malloc() function of the stdlib.h library to store how much memory you need, for example:

char *nome_rua = (char *)malloc(sizeof(char)*a);

Then you can copy the contents of the buffer to your variable, using the strcpy() function from the string.h library

Source: https://www.tutorialspoint.com/c_standard_library/string_h.htm

You need to malloc (a+1) positions, because the string must have \O, which delimits its end.

And also, you can use the function

char *strncpy(char *dest, const char *src, size_t n)

Because then you would copy only the amount of characters read from the buffer.

Scroll to Top