Tuesday, July 28, 2009

C question?

C/C++





(char *frase; int contador;)


whats the meaning of the next sentence?


"for(contador=0; *(frase+contador); contador++)"





What i dont understand is *(frase+contador), what does this means exactly?

C question?
Short answer:


*(frase+contador)


is the same as


frase[contador]





Long:


*() means "dereference a pointer", or "the thing at the address"


"frase + contador" is pointer arithmetic and means


(the address contained in frase) + contador * (the size of the thing pointed to by frase)





So the for loop will terminate when it hits a NUL (0x00) character.





P.S. you probably need to initialize frase as as well as contador.
Reply:() DOES NOT mean dereference a pointer... it's only grouping an expression. The dereference operator is *.





Rolling on the floor laughing... Report It

Reply:frase is a string. contador is a counter (as the - spanish - names says). *(frase+contador) is the character located at (contador) postion in this string.





for instance if contador=0, it's the first character of frase, etc.





Since it's in the condition part of the loop, this instruction is testing for the null character (end of string). The loop is incrementing contador till the null (end of string) character.


No comments:

Post a Comment