Reading an array of strings in C

I want to read a set of rows in an array. The size of the array must be determined at runtime using mallocor alloc, that is, the number of lines is taken as input. I tried the following code, but it does not work.

char *array;
array=(char*)malloc(sizeof(char)*t); //t is the size of array
for(int temp=0;temp<t;temp++)
{
    gets(a[temp]);
}

The same thing works with an array of integers.
Please help me find a solution.

+3
source share
4 answers

C does not have automatic native support for storing strings, there is no variable that is a "string", and can automatically grow to hold the correct number of characters. You need to allocate memory yourself.

, , - . , gets() , , undefined. , . , .

, , , . , , , , , , , realloc(), , .

gets(), . fgets(), .

+5

, , , .

, malloc() char * PLUS .

, gets() , . fgets(). :

char *fgets(char *restrict s, int n, FILE *restrict stream);

, stdin.

, -

char * read_one_line(uint32_t maxbufsize)
{
    char * s = malloc(maxbufsize);
    if (!fgets(s, maxbufsize, stdin)) {
        free(s);
        return NULL;
    } else {
        char * s2 = realloc(s, strlen(s)+1); // +1 for the NUL at the end
        if (s2) {
            return s2;
        } else {
            return s; // should never happen as the memory block is shrinked
        }
    }
}

, , , .

+1

(char*):

char **array;
array = (char**)malloc(sizeof(char*)*t);

( 50 ):

int i = 0, m = 50;
for (i = 0; i < t; ++i)
    array[i] = (char*)malloc(sizeof(char)*51); // 51 = 50 characters + '\0'

, :

for(i = 0; i < t; ++i)
    scanf("%50s", array[i]);

gets scanf (%50s= 50 + '\0').

+1
source

Just remember that there must be a character at the end of the character array NUL.

therefore, t+1allocate memory bytes with allocor malloc.

tfor characters and 1 byte for the trailing character NUL.

after your loop for, i.e. out of loop, just write

a[temp] = '\0';

then you can take it to work.

I hope this works.

it will look like this

char *a = malloc(sizeof((char)*(t+1)));//t is number if characters
int temp;
for(temp=0; temp<t; temp++) {
    gets(a[temp]);
}
a[temp] = 0;

then print the array and you get a string.

printf("%s",a);
0
source

All Articles