-
Problem with the pointer
Hello, I am trying to find a reason why my program doesn't work. It is the last challenge in chapter 9 from "C Programming for the Absolute beginner".
When I add a name, and want to print it later (using function printBook) my ptrC is always 0, although I am incrementing it in function addEntry? What I am doing wrong?
Thanks for helping
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct phonebook {
char name[10];
int number;
} pb;
void printBook(pb *, int *);
void addEntry(pb *, int *);
main()
{
int counter = 0;
pb pb1[5] = {0,0,0,0,0};
int iSelection;
while ( iSelection != 3 ) {
//system("clear");
printf("\n****Phone Book ****");
printf("\n\n1\tAdd new entry\n");
printf("2\tPrint out the book\n");
printf("3\tQuit\n");
scanf("%d", &iSelection);
switch (iSelection) {
case 1:
addEntry(pb1, &counter);
printf("\n%d", counter);
break;
case 2:
printBook(pb1, &counter);
break;
} //end switch
} //end loop
printf("\nBye!\n");
} //end main
void addEntry(pb * pb2, int *ptrC)
{
char name[10];
char *n;
if ( *ptrC < 5){
printf("\nAdd a name: ");
n = gets(name);
gets(name);
strcpy(pb2[*ptrC].name, n);
printf("\n%s", pb2[*ptrC].name);
printf("\n%d", *ptrC);
//printf("\nAdd a number: ");
//scanf("%d", pb2[*ptrC].number);
*ptrC++;
} // end if
else
printf("\nPhone book is full!");
}
void printBook(pb * pb2, int *ptrC) {
int x;
if (*ptrC != 0 ) {
for ( x = 0; x < *ptrC; x++) {
printf("\nName: %s\n", pb2[x].name);
printf("Number: %d\n", pb2[x].number);
} //end loop
} //end if
else
printf("\nNo entries!");
}
-
In addEntry() replace
*ptrC++ with (*ptrC)++; or *ptrC = *ptrC + 1;
-Yogi
My Blog — Blog by Yogindar
-
-
Can you explain WHY it worked? If you can't, you'll be doomed to making similar mistakes in future.