Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

receiving strings from keyboard and storing base address in array of pointers...

Status
Not open for further replies.

borkut

Programmer
Mar 12, 2013
5
void main()
{
char *names[6];
int i;
for(i=0;i<6;i++)
{
scanf("%s",names);
}
getch();
}

i am writing this code and compiller is not giving any error.i am using dev c++.why error?
 
You haven't allocated any space for the names. Say you allow up to 99 characters. Change the code to
Code:
names[i] = malloc(100);
scanf("%s",names[i]);
 
Also, your array is too small. Your loop goes from 0 to 6 which is a total of 7 iterations of the loop. Your array "[tt]names[][/tt]" is only 6 long.


 
the code that i have given is not giving any compile time error.but at execution time it is failing to execute.why?
 
Oops, my bad. [bigsmile]

Read it too fast.

Failing to execute? Does it actually not execute, or does it just do nothing? That's two different things.

Do you get an error message?

 
output screen is coming and then when i am entering a string, a window is coming and its saying that myprogram.exe has stoped working.
 
Have you made the mod I suggested? What does your program look like now?
 
to XWB,

using ur code(modification) my program is executing well.but i want to know why my code is not doing well.

char *names[6] in this cose 'names' is an array of pointers to string.

so whwn i m using
scanf("%s",names); this means that i m passing a pointer variable to scanf function.and pointer
variable holds an address so thats correct that i m passing an address to scanf function
and when i m enetering a string from keyboard then it should store the base address of
that string into that names's address.
 
A char* is just a pointer to a location: there is no where for it to store the information. It does, as you say, store the data in the address of the given string. As you have not initialized the string, it has nowhere to store it. With the mod I posted, it allocates space for program to store the information before reading in the data. So now, it has somewhere to store the data so it does not crash.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top