How to store any string in C?

6

How do I store a string ) without first knowing the size of this string , for example:

#include<stdio.h>
int main (){
char nome[];     /* a array não tem tamanho determinado porque o input ainda
                  não foi dado */
printf("Qual o seu nome?\n");
scanf("%c", &nome[]);    /* não sei como colocar o input na array */
return 0;
}
    
asked by Vitor Matos 14.01.2017 в 14:30

3 answers

6

In your example just put 1 because you are only reading 1 character through %c . So I did not even need the array . But you have a solution if you want string . You have other syntax errors.

The basic technique is to create a buffer (the nome variable in your case) for the highest possible name you want to accept and still put a restrict of how many characters can come in that buffer (use scanf() pure is a tremendous security flaw).

You have a question about why you need to create a buffer of a given size .

In general this is not problematic, unless you need to allocate a very large space even, which is highly unlikely for scanf() .

If it is very important to allocate the required size at one time, you may be able to ask what size to allocate beforehand, then use the variable to create the array :

int tamanho = 0;
scanf("%d", &tamanho);
char nome[tamanho];

It only has a small detail, as this will be allocated in the stack and it is not so big, if this size is too large will give problem. In exercise goes beauty. In real application, this is not the way to do it.

Actually the most used technique is not to use array in stack , but a dynamic allocation in heap through malloc() . You still need to know the size beforehand.

If it is really necessary to allocate memory as needed to theoretically save memory, the solution usually does reallocations. Many programmers create a general function to manage this. What is done is to go reading the characters and allocating in a buffer , when it fills it creates another buffer and copies what was in the previous one and continues there. This can be done even by increasing character by character. Obviously the performance is not the best, but for a keyboard typing is irrelevant. There is a relocation technique ( realloc() ) that avoids manual copying and in some cases even full copy of the content.

A code that does this would be like this (do not consider ready for use in production, I would not even do it for real, but it's easy to understand):

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

int main(void) {
    int size = 0;
    char *nome = malloc(2); //espaço extra para 1 caractere mais o terminador de string 
int tamanho = 0;
scanf("%d", &tamanho);
char nome[tamanho];
while (1) { if ((scanf("%c", &nome[size])) == 1) { nome[size + 1] = '
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int size = 0;
    char *nome = malloc(2); //espaço extra para 1 caractere mais o terminador de string %pre%
    while (1) {
        if ((scanf("%c", &nome[size])) == 1) {
            nome[size + 1] = '%pre%'; //coloca o terminador
            if (nome[size] == '\n') {
                break;
            }
            nome = realloc(nome, ++size);
            if (nome == NULL) {
                printf("Ocorreu algum problema");
                break;
            }
        } else {
            printf("Ocorreu algum problema");
            break;
        }
    }
    printf("%s", nome);
    free(nome);
}
'; //coloca o terminador if (nome[size] == '\n') { break; } nome = realloc(nome, ++size); if (nome == NULL) { printf("Ocorreu algum problema"); break; } } else { printf("Ocorreu algum problema"); break; } } printf("%s", nome); free(nome); }

See running on ideone . Also I put it in Github for future reference .

    
14.01.2017 / 14:58
2

Now, if we are using gnu cc (gcc) - usual in Linux and available for everything platform - or any compatible implementation with POSIX 2013, we can use "%ms" to read by allocating the required space:

#include <stdio.h>

int main(){
  char *nome;
  scanf("%m[^\n]",&nome);   // lê linha, alocando o espaço necessário
  printf("bom dia, %s\n", nome);
  //   free(nome);
  return 0;
}

\ thanks {@hugomg}

    
16.01.2017 в 19:49
0

Even though it is not a good practice for me to see in this language, here is a link with the same question Link , you can do a dynamite allocation in memory so that it changes according to the size of your string.

Remembering that Char has a maximum size that can be entered.

I hope I have helped!

    
14.01.2017 в 14:55