I was reading through my programming book when I came upon two programs-one is a revisement of the other. The programs get your name, then print it on the screen, then print it backwards using pointers. The first version uses a for loop to get input
Code:
for(i=o; i<MAXSTRING; i++)
{
buff[i]=getch();
printf("%c", buff[i]);
if(buff[i]==ENTER)
{
buff[i]= '\0'; /*puts null termination at end of string*/
break;
}
}
the second version uses a pointer
Code:
int main()
{
char c, buff[MAXSTRING], *cptr;
int length;
cptr=buff;
printf("Enter your name: ");
while( (c=getch()) != ENTER)
{
*cptr=c;
printf("%c",*cptr);
cptr++;
}
*cptr='\0';
.......
}
I noticed that when the pointer is used it allows you to input past MAXSTRING (I used 15). I was wondering if there was a way to check to ensure that input doesn't overflow only using *cptr so that another variable doesn't have to be used. I tried adding an if statement inside the while loop to check if the value of buff[0] plus MAXSTRING would equal the value of *cptr (plus 15 bytes because it is only a char), and then if it was equal it would exit the loop. I tried this and it doesn't work
Code:
while( (c=getch()) != ENTER)
{
if(cptr==(&buff[0]+MAXSTRING)
{ break; }
else
{
*cptr=c;
printf("%c",*cptr);
cptr++;
}
}
Can this be done, and if so how?