-
Help with error beginner
I am trying to write a simple program that takes in a string, reverses the letters in it and displays the result. I have not got it finished but am stuck as I keep getting this error:
Application Error
The instruction at "0x004010a7" referenced memory at "0x00000065". The memory could not be "read".
this is the code that I have is not much but it is simple and I cannot see the problem. This error only occurs when either of the printf statments are included
[code]
#include <stdio.h>
char *p;
int main(void)
{
char string;
printf("Type in a string: ");
string = getchar();
p=string;
printf("%s\n", string);
printf("%c\n", *p);
}
[code]
I am lost can you help please.
-
I see you made some improvements...
Take a look again at Hammers comment in your previous thread. Don't use global vars unless you have to.
You are using int main, so return something at the end of your main function.
-
still have error
ok have pur in a return now and removed all the global variables, I have looked over the printf statment and gone through it with my book and am still none the wiser as to where the error is coming from.
[code]
#include <stdio.h>
int main(void)
{
char *p;
char string;
printf("Type in a string: ");
string = getchar();
p=string;
printf("%s\n", string);
printf("%c\n", *p);
return 0;
}
[code]
-
Code:
{
char *p;
char string;
printf("Type in a string: ");
string = getchar();
p=string;
printf("%s\n", string);
printf("%c\n", *p);
return 0;
}
How many threads do you want? Keep to one please. Also, the last code tag needs a forward slash to make it work (see my signature!)
Now to store a string you need an array of chars. Calling a variable string, does not make it one. "char" is a single byte, so this:
>char string;
is giving you variable called string, which is one byte long. Therefore is it not a string.
You need something like this:
>char string[100];
which will give you 99 bytes to store text, and 1 byte for the null terminator that ends the array, and makes it usable as a string.
At your level, I wouldn't bother using pointers (the *p in your code). Just get to grips with basic the concept of arrays first.
Here's one version (there are many ways) :
Code:
#include <stdio.h>
int main(void)
{
char string[100];
printf("Type in a string: ");
if ((fgets(string, 100, stdin)) != NULL)
{
printf("%s\n", string);
}
return 0;
}
Compare this, and research your books. Post again if you have any more questions.
-
Remember that the fgets function also puts the newline character in your buffer.
Here's a link to the fgets manual page
-
Piece of cake:
Code:
static void printRev ( void )
{
int ch;
if ( ( ch = getchar() ) != '\n' )
printRev();
putchar ( ch );
}
-Prelude