How to read a line in C

Asked

Viewed 1,116 times

2

How to read a row of integers and store in a dynamically sized array ?

Currently I read the line as string(although the input is only integers) using gets, only way it worked.

The code is like this:

    type def struct{char entradas[50];} Processo 

    int main(){[...] Processo processos; gets(processo[i].entradas); }

And it works, only I need it to be variable this size of inputs[]

1 answer

2

You might as well continue with what you are doing and create a vector of a virtually unlimited size e.g entrada[500000];

Or create a buffer and load the items partially :

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

void* vetgen(void *vetor,int newsize,int size){
    void *newarr=malloc(newsize);
    memcpy(newarr, vetor,size);
    free(vetor);
    return newarr;
}
int main(){
    int* vetor,i,aux=1;
    vetor=malloc(sizeof(int)*256);
    do{
        scanf("%d ",vetor+i);
        i++;
        if(i%256==0){
            vetor = (int*) vetgen(vetor,i*(aux+1),i*aux);
            aux++;
        }
    }while(!feof(stdin));
}

This code above is just to give you an idea, to read C entries from stdin recommend using the fgets() e. g fgets (buffer, 256, stdin);

  • 3

    Without ever releasing the previous buffer? Beware there! I would recommend using the realloc in that case.

  • I forgot to use the free() thanks for the warning, already corrected. I prefer to use the malloc() even, I don’t know why else I’ve always had to do more validations with realloc. (from my previous experiences it seemed to me to be less robust than the malloc() + memcpy().

  • 3

    The advantage of realloc is that it can find free memory that is right after buffer and increase allocation without creating a new one or copying the data. It will do malloc+memcpy+free only if there is no space. So it will be more efficient.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.