problem with pointer notation in for-loop
Having a bit of problem understanding why I am getting a
Segmentation fault here
I know it has something to do with my loop printing the
reverse of the message array input in first for-loop code
What is it I am not seeing???
Code:
#include <stdio.h>
#define LENGTH 100 /* maximum length of message array */
main()
{ /******************************/
char message[LENGTH]; /* declare all variables */
char *ptr;
/*************************************************/
/* this loop stores message in array with pointer*/
/* pointing to it's elements */
/*************************************************/
printf("Enter your message : \n\n");
for (ptr = (message -1) ; (*ptr = getchar()) != '\n' ; ptr++) {
;
ptr = "\0"; /* sets pointer to NULL */
}
printf("\n");
/***********************************************/
/* this loop take message array and prints */
/* in reverse using decrementation of pointer*/
/***********************************************/
printf("Here's your message in reverse: \n\n");
for ( ptr ; ptr >= message; ptr--){
putchar(*ptr);
}
printf("\n\n");
return 0;
}
getting garbage as output
I am almost done here, but still getting
weird characters before the array prints in reverse
(last for loop controls this)
What is still wrong???
Code:
#include <stdio.h>
#define LENGTH 100 /* maximum length of message array */
main()
{
/*****************************/
char message[LENGTH]; /* declare all variables */
char *ptr;
/************************************************************/
/* this loop stores message in array with pointer pointing */
/* to it's elements */
/************************************************************/
printf("Enter your message : \n\n");
for (ptr = message ; (*ptr = getchar()) != '\n' ; ptr++)
;
ptr = "\0"; /* sets pointer to end of message */
printf("\n");
/******************************************************/
/* this loop take message array and prints */
/* in reverse using decrementation of pointer */
/******************************************************/
printf("Here's your message in reverse: \n\n");
for ( ptr=&message[LENGTH]-1 ; ptr>=&message[0]; ptr--){
putchar(*ptr);
}
printf("\n\n");
return 0;
}
here's INPUT AND OUTPUT run
*******************************************
Enter your message :
how are you doing?
Here's your message in reverse:
,ü¾ÿ(Èû¾ÿ¼¨<ÿ`3ÿ¼¨<ÿ>ÿ>ÿ /* why is this printing ??? */
?gniod uoy era woh /* this is correct output */