1

I'm trying to practice some c++ stuff and have gotten stuck on something which has been difficult to google or find the answer too.

basically say we have:

char* myarray[] = {"string","hello", "cat"};

how would I got about say getting myarray[1] which is "string" and then traversing through the letter s t r i n g.

I was looking at vectors and wonder if that is the route to take or maybe taking myarray[1] and storing it into another array before iterating through it. What is the best way of doing this

2
  • 2
    First of all, "string" is saved in myarray[0], not myarray[1] (arrays start at zero in C++). Second, have you tried a vector of std::strings instead? While this is not a real answer to your question, try to accustom yourself to the standard library, which will take some work from you. Commented Mar 14, 2013 at 19:06
  • 1
    Basically, never say we have char* x = "...";. String literals are immutable, and should be char const*. Commented Mar 14, 2013 at 19:31

2 Answers 2

4

That's very easy in C++11 (using std::string rather than a pointer to an array of characters):

#include <iostream>
#include <string>

int main()
{
    std::string myarray[] = {"string","hello", "cat"};
    for (auto c : myarray[0]) { std::cout << c << " "; }
}

Output (live example):

s t r i n g
Sign up to request clarification or add additional context in comments.

Comments

3

The following code:

for(int i = 0; i < strlen(myarray[0]); i++) {
    printf("%c\n", myarray[0][i]);
}

Will print out

s
t
r
i 
n
g

If you're looking to practice C++ and not C, I suggest learning std::string and std::vector. They are not always the solution but usually using them first is the right answer. The memory layout of std::vector<std::string> will be different and it is important to understand this.

6 Comments

This is horrible. If you really want to use the C style strings, then at least move the strlen out of the loop (and using pointers would be more idiomatic both in C and in C++).
@JamesKanze any compiler should move the strlen out of the loop for you, but I agree with you anyway
@Dave The compiler can only move strlen out of the loop if it knows what's in strlen. The way most compilers I've seen are set up, they don't.
@James Any sane compiler will make this optimization. Here is a list of functions that GCC is particularly good at optimizing gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
@James Both clang++ and g++ do on the most recent Ubuntu. What mainstream compiler do you have in mind?
|

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.