Page 1 of 1

strings/ printing strings

Posted: Tue Apr 22, 2003 2:37 pm
by slacker
in c/c++ you can declare a string:

char str[5]="hello"

and the compiler puts the chars right next to each in memory...

but if you try to print this string to the screen:

char *temp;
*temp=str[zero]; (zero = 0) mega tokyo format messes it up
print(temp);

it will print the first char 'h' and then junk. why does this happen because all the chars should print because they are right next to each other.
----------------------------------------------------------------

char *str="hello"
print(str);

this will print the string correctly. why?
arent the two the same? how would i go about print an array of chars that is declare like: char str[5]="hello"?

Re:strings/ printing strings

Posted: Tue Apr 22, 2003 3:19 pm
by jamescox3k
A few things here the text hello is not 5 chars long its 6. {'H', 'e', 'l', 'l', 'o', '\0'} dont forget that null. But your problem atualy lies here

char *temp;
*temp=str[zero]; (zero = 0) mega tokyo format messes it up
print(temp);

char *temp;
*temp=&str[zero]; see the & (address of str zero)
print(temp);

You was appling the value of str[zero] to your pointer not the address besides you should simply be able to put print(str) because arrays and points are realy the same thing.

Re:strings/ printing strings

Posted: Tue Apr 22, 2003 3:28 pm
by jamescox3k
Dont you just hate it when a mistake comes from a typo?

Re:strings/ printing strings

Posted: Tue Apr 22, 2003 3:32 pm
by slacker
u dont need the & to designate the address of...

Re:strings/ printing strings

Posted: Tue Apr 22, 2003 3:47 pm
by Pype.Clicker

Code: Select all

char *temp=str[0];
shouldn't compile without issuing a warning on a good compiler.

Code: Select all

char *temp=str+0;
and

Code: Select all

char *temp=&(temp[0]);
are the two syntax i use. I had too many weird results with

Code: Select all

&str[0]
...

btw, to avoid MT [ O ] bug, just put your code between [ code ] and [ / code ] tags (spaces are to be removed :)

Re:strings/ printing strings

Posted: Tue Apr 22, 2003 4:23 pm
by jamescox3k
You do need the & sigh for address of. Thats what its for...

This should aslo work

temp=str;