Home Forums C Programming Understanding Pointers and Strings

Viewing 4 reply threads
  • Author
    Posts
    • #2183
      JonathaThurston
      Participant

      Hey Guys,

      I have a question regarding pointer arithmetic as I find it very hard to grasp it. Well to be totally honest I do not understand the concept at all so I wrote this program which sends a char array to a function and prints out a string of characters from a certain offset to a certain length.

      I am having trouble with the loop in the function can you please help me understand it.

      Thanks.

    • #3536
      GWILouisaxwzkla
      Participant

      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 :

      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:

      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:

    • #3537
      JonathaThurston
      Participant

      Hey dman thanks for explaining it makes more sense now. Is it possible to avoid making *index a pointer to the array and do the manipulations on *w instead?

    • #3538
      GWILouisaxwzkla
      Participant

      Heres how I might do this ( this uses pointer arthimatic instead of indexes ) :

    • #3539
      JonathaThurston
      Participant

      Yea that makes more sense actually, and its more readable than a for loop.
      Thanks

Viewing 4 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.