-
Printing problems
I'm trying to write a program that all yous to enter a name into an array and them print that name when you type in it's index. The print command is in a function separate from the main one. The problem is that whenever I try to print that name, I always get (null).
Here is the code I am working with:
Code:
char *first[50];
char *last[50];
char blank[50];
char blank2[50];
int _tmain(int argc, _TCHAR* argv[])
{
printf("Enter a name (last, first): ");
scanf("%s %s", &blank2, &blank);
first[i] = blank;
last[i] = blank2;
printf("%s %s", &*last[i], &*first[i]);
i = i + 1;
getchar();
//To test the program, I have it print out the name I just entered. This part works works fine.
printf("Enter the index of the name you wish to see (realize that the numbers start a 0): ");
scanf("%s", &number);
print(number);
}
void print(int index){
printf("%s %s", &*last[index], &*first[index]);
getchar();
//this is the problem area.
//I want to print the name associated with the index I inputed, but all I get is two "(null)'s",
//one for the first name and one for the last name.
}
By the way, I'm programming using Visual Studio.
-
Hi
First of all, you have to declare a function prototype at the begining of your code so the linker knows where to link your function calls. Add something like this at the begining of your code (after global variables before main())
void print(int index);
If I were you, I would use a while() loop and a control phrase to finish the loop to get the entries. In the way you use, the user can enter only one name! Store the entered named into a char* array. And fetch and diplay the value by using an index.
-
ok be prepared to make a few changes in your code:
>scanf("%s %s", &blank2, &blank);
blank2 and blank alread are addresses ,so it should be scanf("%s %s",blank2,blank);
>first[i] = blank;
u have not declared and initiliazed i any where;
so use int i=0 or int i =1 as u prefer before this assignment.
>scanf("%s", &number);
it should be int number; scanf("%d",&number);
-
I did initialize i and number, I just forgot to copy that part of the code. Sorry about that. Also I put the "&'s" in there because the program will have run-time errors if I don't have them.
-
Upon further inspection, it turns out that I was trying to solve the wrong problem. I put in a few more print statements to test the output and it turned out that I wasn't writing to the array properly.
So any, I figured out what I was doing wrong and it works now. Thank you for your help, everyone!
-
Except for one thing....
is identical to
and gets() should be avoided at all cost... see this