Stelios Papamichail
Stelios Papamichail

Reputation: 1290

Pointer arithmetic gone wrong

I'm trying to use a char * to store a string and since the pointer is pointing to the memory location of the first char of the given string, i tried using pointer arithmetic (ptr++) to move on to the next char (since they are stored sequentially). However, in my example program the size of the "string" is 22 but when i try running a for loop as seen below, it only runs 12 times. Any idea why? Have i missed something important on how pointer arithmetic works?

#include <stdio.h>

int main(void) {
  char *strVar = "testfordifferentlength";
  int i,timesCalled=0;
  printf("\nLength = %d\n\n",strlen(strVar));
  for(i=0;i <= strlen(strVar);i++){
    printf("%c",*strVar);
    strVar++;
    timesCalled++;
  }
  printf("\n\nFor loop run %d times!\n",timesCalled);
  return 0;
}

Upvotes: 1

Views: 116

Answers (1)

John
John

Reputation: 2425

The issue is that you're calling strlen(strVar) on every condition check (inefficient as-is), and also modifying where strVar points at the same time. Store the initial size in a variable and compare your index against the initial size, rather than the remaining length of the string. Also, you probably want to use < rather than <= in your condition since you're starting at 0. Otherwise, you're also iterating over the terminating NULL character since strings in C are null-terminated.

#include <stdio.h>

int main(void) {
  char *strVar = "testfordifferentlength";
  int i, timesCalled = 0, length = strlen(strVar);
  printf("\nLength = %d\n\n",length);
  for(i = 0; i < length; i++){
    printf("%c", *strVar);
    strVar++;
    timesCalled++;
  }
  printf("\n\nFor loop run %d times!\n", timesCalled);
  return 0;
}

For further understanding, imagine each loop iteration with your initial code:

i = 0, strVar = "testfordifferentlength", length = 22, output is 't'
i = 1, strVar = "estfordifferentlength", length = 21, output is 'e'
i = 2, strVar = "stfordifferentlength", length = 20, output is 's'
i = 3, strVar = "tfordifferentlength", length = 19, output is 't'
...
i = 11, strVar = "erentlength", length = 11, output is 'e'
And this point your loop ends

Essentially, you'll end up printing (strlen/2) + 1 characters, since you're increasing your index by 1 and reducing the length of the string by 1 each loop iteration.

Upvotes: 6

Related Questions