Using an array with pointers in C
Hello i'm practising C and i have a little problem with the following code. First of all, my program just reads the input from the user and if there is memory availble, it stores it, otherwise it makes nothing.
I have an array of pointers to char called "lines" and an array of chars for the temporary storage of the input called "line".
#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 ;
Then i will check if my array of pointers has space and the input is non-zero. I do it in a for-loop to fill the array and normally the for-loop should stop when i type in nothing and just press enter or when the array is full. If there is space i will check if there is enough memory in the space where the pointer is pointing to. If that's ok (!= NULL), the program copies the input from gets(line) in the memory.
for (n = 0; n < MAXLINES && gets(line) != NULL; n++)
{
if ((lines[n] = malloc(strlen(line) + 1)) == NULL)
exit (1);
strcpy(lines[n], line);
}
The rest of the code is just for the output and freeing of the memory.
for (i = 0; i < n; i++)
{
puts(lines[n-i-1]);
free(lines[n-i-1]);
}
return 0;
}
Now the problemis , that the program runs without any errors, but it's not working as i want. It is just performing a infinte loop where i can type in as long as i want, what i want without any reaction.
gets
doesn't return NULL when you type an empty line, if that's what you tried to check for. It will still be an empty string. You'll need to check if the first character is a \0
if you want to look for empty lines.
On a side note, gets
is extremely unsafe since it will overrun your buffer if your line is too long and cause evil bugs. Use fgets
instead, it lets you specify the size of your buffer. (Note that fgets will add a \n
to the end of your string, even if it's an empty line.)
Well for a start, I suggest reading the following about why you should avoid using gets()
. I suggest using scanf()
or fgets()
instead...
http://www.gidnetwork.com/b-56.html
then note that you're doing a loop to 100 taking input, and only after all 100 are you outputting. So you'll need to enter 100 lines of input currently before you see anything...
You're not checking for an empty line.
You need something like:
if('\0' == line[0])
{
break;
}
And use fgets() not gets(). It's safer. However you then need to do:
if('\n' == line[0] || '\r' == line[0])
{
break;
}
Well, how do you terminate your input? Entering an empty line won't help because line will be ""
not NULL
. Have you tried pressing Ctrl+Z in the console (if it's windows)?
精彩评论