How do I save an undefined string in a structure?

5
#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 what is the best way to save "street name" with an unknown size in the "ecoponto ecoponto" structure.

    
asked by anonymous 05.01.2017 / 21:14

1 answer

2

To save a string of unknown size without spending extra memory, you need to read the street name in a buffer, a very large variable that can support any street name, for example, size 1000. Then use the string library . and its strlen () function, which returns how many characters a string has and use strlen (buffer).

Now you know how many characters the street name has, 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, and you can use the function strcpy () of the library string.h

Source: link

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

And also, you can use the

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

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

    
05.01.2017 / 21:25