strings/ printing strings

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
slacker

strings/ printing strings

Post 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"?
jamescox3k

Re:strings/ printing strings

Post 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.
jamescox3k

Re:strings/ printing strings

Post by jamescox3k »

Dont you just hate it when a mistake comes from a typo?
slacker

Re:strings/ printing strings

Post by slacker »

u dont need the & to designate the address of...
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:strings/ printing strings

Post 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 :)
jamescox3k

Re:strings/ printing strings

Post by jamescox3k »

You do need the & sigh for address of. Thats what its for...

This should aslo work

temp=str;
Post Reply