Home › Forums › C Programming › Understanding Pointers and Strings › Re: Re: Understanding Pointers and Strings
To understand the problem completely, remember that arrays are configured as contiguous blocks of memory ( the first index in memory precedes the next and so on ) and realize the fact that pointers are simply variables that hold the address of other variables ( the size depends on your hardware and operating system ). Also keep in mind that in C the semantic value of an array’s name is the address of the first item in the array ( array [ 0 ] ). So that in your program you have a situation like :
1 2 3 4 | <br /> <br /> draw(words + 11, len); //pass in the address of the 11th 8-bit item in memory, words [11]<br /> |
since the array looks like this in memory ( let 0x0065fd94 be the first address of the array ):
memory address item
0x0065fd94 ‘T’
0x0065fd95 ‘h’
0x0065fd96 ‘i’
0x0065fd97 ‘s’
…………..
and so on your loop:
1 2 3 4 5 6 | <br /> <br /> for(index; *index != *(index + len); index++)<br /> putchar(*index);<br /> }<br /> |
starts at index == words [ 11 ] which is ‘h’ and continues until ( *index == *(index + len); ) . But since * ( index + len ) is words [ 32 ] == ‘h’ your loop never executes. I think what you wanted to do is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <br /> #include <stdio.h><br /> #include <iostream.h><br /> <br /> void draw(char *w, int len);<br /> <br /> int main()<br /> {<br /> <br /> char words [ 100 ] = ("This is my hundredth attept st this extremely annoying task :)");<br /> char * index = NULL;<br /> int len = 21;<br /> <br /> <br /> <br /> draw( words + 11, len );<br /> <br /> <br /> <br /> return 0;<br /> }<br /> <br /> void draw ( char * w, int len )<br /> <br /> {<br /> char * index = NULL;<br /> int i = 0;<br /> <br /> index = w;<br /> <br /> putchar ( 'n' );<br /> for( ; i < len ; index ++ , i ++ )<br /> {<br /> putchar ( * index );<br /> }<br /> putchar ( 'n' );<br /> }<br /> <br /> <br /> <br /> |