0

I know that for a given integer array, a pointer to that integer array, I can access the integer array using something like this:

int main(){

  int x[4] = {0,1,2,3};
  int *ptr;

  ptr = x;

  for(int i = 0; i < 4; i++){
    printf("%d", *(ptr+i));
  }
  return 0;
}

Now say I have a character array instead, doing the same thing doesnt work.

int main(){

  char x[4] = "Haha"; 
  char *ptr;

  ptr = x;

  for(int i = 0; i < 4; i++){
    printf("%s", *(ptr+i));
  }
  return 0;
}

Apparently *(ptr+i) in the first code increments the pointer to the integer 4 bytes each time. It doesnt work for the second code. How do I use the same notation for character array? I think the idea is to increment one char each time.

1
  • 1
    %s is for an array of chars (null terminated string), %c is for a single character. printf("%c", *(ptr+i)); Commented Feb 4, 2020 at 2:17

1 Answer 1

2

You print each letter after a loop so you should correct your source code: printf("%s", *(ptr+i)); into printf("%c", *(ptr+i)); I think you should change char x[4] = "Haha"; into char x[5] = "Haha"; because, maybe in this case it doesn't cause any errors but sometimes, you will get overflown, be careful!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.