-1

How can I transverse a char array using a pointer? Is there a way to transverse an array using a pointer?

I have a program using a char array and a for loop but I want to be able to use pointers to move through the array of chars. However I am not sure how to use a pointer with an array of chars.

#include <stdio.h>
#include <string.h>

int main() {

  char arr[] = "abcde";
  int length = strlen(arr);
  for(int i = 0; i < length;i++)
  {
       printf("%c ", arr[i]);
  }
  return 0;
}

I need to change the way I transverse the array, but not sure how to do it using just pointers. It also needs to work in c and c++.

Caperneoignis
  • 1,353
  • 13
  • 16
  • 1
    Do yourself a favour and lose the C++ tag. – user4581301 Apr 01 '16 at 16:37
  • It can work in both however, so that is why I tagged it that way. I am starting to see you point though. However, I had to learn to use pointer arthimatic when I started in C++ so that is why I thought it was okay to place it. – Caperneoignis Apr 01 '16 at 16:42
  • The string is supposed to be "abcde" please do not change it back to the wrong array type, because that is not what it is supposed to be. That was an oversight by me. – Caperneoignis Apr 01 '16 at 16:48
  • 1
    @Caperneoignis Please don't go in a rollback war with me. The way you have changed your (still unclear) question is rude, and disrespects my efforts to give a concise answer, what's actually going on. – πάντα ῥεῖ Apr 01 '16 at 16:49
  • 1
    @πάνταῥεῖ it is not a roll back war. It was a mistake, and I corrected it as you can see below in my answer to my own question. it was an oversight that I corrected. as you can see at the bottom of my question I said I gave an answer to going over a string using a pointer. – Caperneoignis Apr 01 '16 at 16:51
  • 2
    @πάνταῥεῖ Drop the ego. – 8protons Apr 01 '16 at 16:51
  • @Caperneoignis _"Please see below, for why I added this question ..."_ The question is for formulating the question, the answers below are for possible answers. – πάντα ῥεῖ Apr 01 '16 at 16:57
  • @πάνταῥεῖ okay, edited the question so it is more inline with what I was trying to formulate as a answer. – Caperneoignis Apr 01 '16 at 17:20

1 Answers1

-1

Okay so after searching and not seeing the answer I have decided to make a question with my own answer. Feel free to critique me, but I felt this could help a lot of people with questions about pointers.

As the title suggest this will be going over how to transverse a char array, string from here on out, using a pointer.

I'm making this question because I forgot how to transverse a string using a pointer, and it took me a minute to rediscover how to do it.

This code should work in both c and c++. I have compiled it using ideone.com and I know it works.

#include <stdio.h>


int main() {

  char *ptr;
  char arr[] = "abcde";

  for(ptr = arr; *ptr;ptr++)
  {
       printf("%c ", *ptr);
  }
    return 0;
}

http://ideone.com/e.js/CC5IZ6

As we can see above, we first make a pointer of type char, *ptr, and then an array of characters in the char arr[]. Then we have 'ptr' point to 'arr' in the first part of the for loop.

The second part of the for loop, is the conditional section, and we are looking for the end of the string using '\0'. By 'de-referencing' 'ptr' using the '*' in front of the variable we can access the information in memory that the pointer is 'pointing' to, which will be one of the characters in the char array. In this case we are looking for the end of the string signified by the '\0' character. I have heard it called many things; however, in C you call it the null character. But I digress, the next part of the for loop is the increment portion which increments the ptr one position each iteration of the for loop.

The for loop allows us to move the pointer by incrementing memory spots that have been allocated for the array of characters. This allows us to use the pointer to move through the array using pointer arithmetic.

To print the items in the array using printf we need to dereference the pointer once again using the '*' symbol(not sure how best to describe it, so if anyone knows a better way please let me know). This gets the item in memory the pointer is currently pointing at and allows it to print it out.

Now what would happen if we didn't use the '*' symbol? Well, the way printf is currently set up, which is to print chars, we will get an error or nothing at all. If you want to see what memory location the pointer is at, and not what is in that memory location, then change printf to 'printf(%p',ptr);' '%p' means print pointer address.

if you are curious please look here for other commands you can send to printf. http://www.cplusplus.com/reference/cstdio/printf/

The result of this is the array being printed out in order "a b c d e".

The reason why printer arithmetic is so helpful is for two reasons. 1. Helps with students understanding of pointers, when you are first starting out, before getting in to advanced c++ items. 2. It makes it possible to use dynamic memory, without pointers and the ability to transverse them, you would have no recourse if your program grew past the allocated amount of memory you first allocated for the program.

That last part is my understanding of pointers in general, I'm sure a guru of c will have a better definition and I'll be happy to modify the reasons.

Please let me know what you think, and feel free to give me an critiques, and I'll be happy to modify this question/answer so we can help members of SO.

Thank you,

Caperneoignis
  • 1,353
  • 13
  • 16
  • 2
    why do you expect `*ptr != '\0'` to be true? – Zdeslav Vojkovic Apr 01 '16 at 16:27
  • @ZdeslavVojkovic good point, should I add ptr != null to the loop? and change it to a while. – Caperneoignis Apr 01 '16 at 16:29
  • 1
    @Caperneoignis No . Strings in C are terminated by `'\0'` and you array is not , so don't pass it to `strlen`. _Right now you need to explicitly add_ `'\0'` . You have a char array but not a string . – ameyCU Apr 01 '16 at 16:30
  • However, I have always been told the null terminator is added to the end of a string in c and c++, so it's the reason I did it that way. Is there a reason it would not be true? I'm just wondering for future use. normally I do both a doe not equal null and check for null termination. – Caperneoignis Apr 01 '16 at 16:31
  • 3
    Why would `ptr` be `null`? You don't have a string but an array of chars. Just declare the `arr` as a string literal: `auto arr = "abcde";` – Zdeslav Vojkovic Apr 01 '16 at 16:31
  • Good point!, let me run a quick check to see if that changes anything. – Caperneoignis Apr 01 '16 at 16:33
  • The null terminator is added to the end of each `const char*` as long as it's initialized with the char's in a string based notation: `"hello world"` since you're initializing it in a `char[]` using brace initialization, you're specifying that there will only be the characters specified within the `{...}` that will be part of your `char[]` – Toppest.Of.Kek Apr 01 '16 at 16:33
  • Okay, I fixed the error, thanks for pointing that out, can't believe I missed that. it is now a string that is assigned to char arr[]. It works after running it through ideone.org. – Caperneoignis Apr 01 '16 at 16:39
  • Why am I getting down votes for? I said I was going to fix the error... – Caperneoignis Apr 01 '16 at 16:46
  • @kfsone Yes, I actually had it the wrong way at first, and they were pointing it out. I have fixed the error, from the information I have gotten since posting. – Caperneoignis Apr 01 '16 at 16:49
  • Nice try at a self Q &A. Yet the answer does not address the question's weakness in using `int` rather than the proper `size_t`, the strange use of `the cast `(unsigned)`, the missing `'\0'` issues (which is call the _null chracter_ in C). – chux - Reinstate Monica Apr 01 '16 at 16:49
  • @chux okay, I'll drop the unsigned cast, wasnt sure how to do a Q&A, just wanted to share how to transverse a char array using a pointer since I didn't really see anything like it on SO. So I'll take a hit for that one. – Caperneoignis Apr 01 '16 at 16:55
  • @Caperneoignis I am not recommending you drop the cast from the _question_. Is is that this _answer_ should have addressed its incorrect usage. – chux - Reinstate Monica Apr 01 '16 at 16:57
  • I don´t think we need this kind of posts on SO. Downvote, sorry @Caperneoignis – Andreas Apr 01 '16 at 16:57
  • @Andreas Answering your own question is _promoted_ on SO. See [here](http://stackoverflow.com/help/self-answer) This particular answer has its weaknesses, but it is in line with SO. – chux - Reinstate Monica Apr 01 '16 at 17:00
  • @chux I was not sure how to do the question part, since I was more concerned with doing the answer part. I will re do the code real quick in the question so the answer seems more logical and in line. – Caperneoignis Apr 01 '16 at 17:06
  • @chux modified the question, so hopefully it works better with the answer, since I'm trying to make this useful to other members. – Caperneoignis Apr 01 '16 at 17:14
  • NUL character, null or NULL pointer – mpez0 Apr 01 '16 at 17:16
  • @mpez0 okay, fixed the portion about the null terminator and is now corrected in the answer. Thanks for pointing it out. – Caperneoignis Apr 01 '16 at 17:19
  • @Caperneoignis Small enhancement for `for(ptr = arr; *ptr != '\0';ptr++)`: `for(ptr = arr; *ptr; ptr++)` – πάντα ῥεῖ Apr 01 '16 at 17:25
  • I change downvote for duplicate. Objections? – Andreas Apr 01 '16 at 17:25
  • @πάνταῥεῖ I like that, it is simpler thanks. – Caperneoignis Apr 01 '16 at 17:26
  • @Andreas well when I search SO I couldn't find an answer that answered my question. so I went ahead and made this. I mean if you want to down vote then you didn't like the question. But I don't see how this is a duplicate. – Caperneoignis Apr 01 '16 at 17:28
  • @Caperneoignis What are your thoughts of this post: http://stackoverflow.com/questions/394767/pointer-arithmetic – Andreas Apr 01 '16 at 17:31
  • @Andreas hmm... I guess I can add my answer to that. When I searched I was looking for transversing an array using pointer arithmetic and for some reason I didn't get any hits back. – Caperneoignis Apr 01 '16 at 17:33
  • @Andreas but you are correct, that is in the ball park of my question. – Caperneoignis Apr 01 '16 at 17:35
  • @Andreas marked the question as a duplicate. – Caperneoignis Apr 01 '16 at 17:36
  • @Caperneoignis I flagged it. Don´t have marking priviliges. – Andreas Apr 01 '16 at 17:42
  • For the future: do not _modify_ the question to match the answer. You are not the only one answering the question. Modify your answer instead. A moving target question is not well received. – chux - Reinstate Monica Apr 01 '16 at 17:42
  • @chux I understand, normally I don't unless someone ask for something. But in this case my question was made in a hurry since I made the answer first and forgot to formulate a question that went with the answer. I hosed myself I know. – Caperneoignis Apr 01 '16 at 17:46
  • @Andreas I know, I accepted it as a duplicate, I was just letting you know I accepted it and because of that it marked as a duplicate. Wasn't accusing you of anything, sorry. – Caperneoignis Apr 01 '16 at 17:47