nk wrote:
Hi,
I'm a newbie on this language. I would be very happy if you help me
about the following issue:
The code below, reads some names(strings), stores them, and stores the
addresses in the pointer array, and writes them out. But it fails and
exits the program. I guess that it's about initializing the array but i
couldn't find a way to make it ok.
--------------------------------------------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
Why include conio.h? It's a non-standard header and there are better
ways of ensuring you see the output of your program than calling getch.
int main()
Better to be explicit about not taking parameters.
int main(void)
{
char *a[50];
int i, numb;
printf("How many entries would you like to make?\n");
scanf("%d", &numb);
What of the user types "one" instead of "1"? Always check the return
value of input functions and the *scanf family of functions. Although in
general it is easier to read the input with fgets (NOT gets, NEVER gets)
and then parse it.
printf("Enter the names please..\n");
for ( i = 0; i < numb; i++ ) {
scanf("%s", a[i]);
Don't use a %s in scanf without specifying an upper limit. It's like
holding a shot glass over your computer, giving the user a hose,
blindfolding him/her so s/he does not know how large the glass is, and
then saying pour in as much water as you want. At some point someone
will flood your computer completely wrecking it. gets has *exactly* the
same problem as the line above.
You have the additional problem that a[i] is a pointer to char which
does not point anywhere in particular yet. So scanf will write to some
random part. scanf does not magically create space for the string it is
reading, you need to do that before you call it. This also means you
need to decide on an amount of space and tell scanf how much space
you've given it.
Further, you are not checking that the user has input a number <= 50.
Having fixed all the other problems, the user could still enter 51 and
blow up your computer.
}
for ( i = 0; i < numb; i++ ) {
printf("%s", a[i]);
}
getch();
On my system that function sends insulting messages to the Chinese
embassy. You could use a standard input function or find out how to get
your environment not to close the window as soon as the program terminates.
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------
Thanks..
All my comments are to help you learn even though many of them don't
address your immediate problem.
--
Flash Gordon
Still sigless on this computer