hi..uhmm..about pointers in C.
char *s;
s="hello";
when u print the *s, the output is garbage or nonesense..
but if u print the value of s alone...hello would appear..why is this so? correct me if im wrong...
the s pointer points to the address of "hello" and when i dereference 8 it should work..by now...
About pointers in C?
I think you're doing it wrong.
You would need something like this:
#include %26lt;iostream%26gt;
using namespace std;
void main()
{
char *s;
char mystring[] = "hello";
s = mystring;
cout %26lt;%26lt; s;
system("Pause");
}
EDIT - I just tried this and it works, have a good day.
Reply:it won't print garbage .
it will just print h;
the pointer s will be just pointing to the first element .
so when you do a *s it will print h
Reply:its like this:
s stored the address location
*s stores the value stored in the first position of s
for printf and all functions that use string (i.e. char *) values, you pass the address and all manipulation etc happens to the value stored at address using address pointer -%26gt; pointer manipulation
when u print as:
printf("%s", *s); --%26gt; this should print junk
but when u print as:
printf("%c", *s); --%26gt; this should print the char at first byte location of s
and if u print as:
printf("%s", s); --%26gt; this should print the entire string stored in s
read a book on pointers, it will take too long to explain here. and its already explained very well in many books.
also there is a chance your current program (as it is) may core dump. this is because u r defining in one statement and then assigning in another. but since you did not allocate memory before proceeding to assign, your program will core dump. to resolve this, use:
char *s="hello";
doing this does definition, allocation of memory and assignation all at the same time.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment