Hi,
I'm a newbie. I need to clear my pointer concepts.
Well, you need to clear your head about what you think you know about
pointers. Most of it is wrong.
the code below gives segmentation fault when i use char* str;
That's lucky. It might have completely hosed your machine. Pointers are
dangerous.
You need headers of some form. Try:
#include <stdio.h> /* For printf and scanf */
#include said:
You mean int main(void) here.
Here, str is a location that could hold a pointer to a region of memory if
one is ever assigned to it. It never gets the chance to hold anything
useful.
printf("Enter a string to reverse\n");
scanf("%s",&str);
You are feeding scanf a pointer to the variable str, a pointer to a
pointer to char. A good compiler would warn you about such things.
Secondly, the program would crash even if you had called scanf correctly.
Since str doesn't hold a pointer to any block of memory, scanf would have
tried to put characters into some random location. This is a very good way
to cause very bad things to happen.
Finally, scanf is a bad function to use in this case. The reason is, it
doesn't know when to stop stuffing characters into an area of memory.
scanf will happily overwrite your whole OS and never give you a chance to
stop it. (Modern OSes will protect themselves these days, but scanf could
easily destroy other data you would rather preserve.)
This function call is quite useless. Not only are you calling it with
bogus data (the random contents of the variable str), but its job is to
compute the length of a string. Calling it without capturing its return
value is pointless.
You should return an int from main, like you said you would above. Try:
return 0;
}
if I use char str[20] it runs fine.
You mean it doesn't crash, even though it should. It still doesn't do
anything sensible.
int main()
{
char str[20];
Here, str is an array of 20 characters. That means you have given the
program a place to put the string you want to type in.
printf("Enter a string to reverse\n");
scanf("%s",&str);
It ought to crash right here. Even better, the compiler should stop and
return an error message. Are you quite sure you know how to operate your
compiler? You are /still/ passing scanf a pointer to a pointer to char,
which isn't what it wants.
strlen(str);
}
Can you please explain why?
Because you need to read a /good/ book on the C language, not whatever
crap you have now. Try "The C Programming Language", Second Edition, by
Brian Kernighan and Dennis Ritchie.