Question:
about pointers in C?
chainz
2007-06-23 05:04:31 UTC
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...
Three answers:
Darth Revan
2007-06-23 05:56:26 UTC
I think you're doing it wrong.



You would need something like this:



#include

using namespace std;



void main()

{

char *s;

char mystring[] = "hello";



s = mystring;



cout << s;

system("Pause");

}



EDIT - I just tried this and it works, have a good day.
ddsa
2007-06-23 13:02:41 UTC
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 -> pointer manipulation



when u print as:

printf("%s", *s); --> this should print junk



but when u print as:

printf("%c", *s); --> this should print the char at first byte location of s



and if u print as:

printf("%s", s); --> 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.
Sumit K
2007-06-24 15:41:24 UTC
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


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...