Using an array with pointers in C

Hi, I'm in C, and I have a little problem with the following code. First of all, my program simply reads the input from the user and, if there is available memory, it stores it, otherwise it does nothing.

I have an array of pointers to char called "strings" and an array of characters to temporarily store input called "string".

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

#define MAXWIDTH 81
#define MAXLINES 100

int main ()

{
    char* lines [MAXLINES];   
    char line[MAXWIDTH];
    int i ;
    int n ;


, , . , , for , . , , , . ok (!= NULL), () .

for (n = 0; n < MAXLINES && gets(line) != NULL; n++)    

        {
            if ((lines[n] = malloc(strlen(line) + 1)) == NULL)  
                exit (1);
            strcpy(lines[n], line);                             
        }


.

    for (i = 0; i < n; i++)
        {
            puts(lines[n-i-1]);
            free(lines[n-i-1]);
        }


    return 0;
}


, - , , . infinte, , , - .

+3
4

, , gets(). scanf() fgets()...

http://www.gidnetwork.com/b-56.html

, 100, , , 100 . 100 , ...

+3

gets NULL, , , . . , \0, .

, gets , , . fgets, . ( , fgets \n , .)

+4

You are not checking an empty string.

You need something like:

if('\0' == line[0])
{
    break;
}

And use fgets () not gets (). It is safer. However, you then need to:

if('\n' == line[0] || '\r' == line[0])
{
    break;
}
+2
source

Ok, how do you complete the input? Entering an empty string will not help, because the string will ""not NULL. Have you tried to press Ctrl + Z in the console (if this is a window)?

+1
source

Source: https://habr.com/ru/post/1778922/


All Articles