0

I need to be able to turn this char* array[SIZE] into a char* example. How can i do this? My problem is that i need to be able to manage the contents of array separately in a pointer like fashion For example if i have:

array[0] = "dog"
array[1] = "cat"
array[2] = "one"

i want to be able to access each one of those elements by incrementing the value of a pointer like this

example = "dog"
example++ = "cat"
example++ = "one"

thanks in advance!!

My main problem is that i need to have all of these values pointed by a pointer, such that when i print my pointer ill have something like this:

printf("example: %s\n", example);
output: example: dog cat one
0

2 Answers 2

2

You can simply do:

char **example=array;

of course it's not a char * (which you asked in the first line), but it does allow the functionality you ask for later.

--- edit --- Your printf requirement cannot be met with this method. In C++ you could build some strange object that would meet both requirements (but with C++ streams, not printf), but you should explain the "big picture", this whole thing smells a lot of XY problem.

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

5 Comments

the problem that i encountered by doing it that way is that i get a segmentation error. How could i avoid getting a seg error?
@user2913269: how would I know? It all depends on how is the rest of your code.
@AndreyT: that requirement has been added after my answer was posted.
Matteo i apologize for that, but i forgot to mention that my program has to be able to move the pointer word by word, and utilize that value as i go
@user2913269: The pointer in the above answer will move word-by-word. However, these words will not be stored as one string. They will be stored as separate words. Your last requirement - the ability to print all words in one shot - is the part that makes no sense and makes the whole thing impossible. Remove that strange requirement and Matteo's answer becomes exactly what you need.
1

Your requirements are mutually exclusive.

It is not possible to have an array of pointers to zero-terminated strings that is at the same time printable "in one shot", as in your printf example.

You will have to reconsider your approach. What you want at this point is not possible.

Comments

Your Answer

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