0

So I have a char array, c, which has characters like this: "HELLO MY NAME"

I want to make a char pointer array, *pCar, so that pCar[0] will have HELLO and pCar[1] will have MY and pCar[2] will have NAME.

I have something like this but it doesn't work.

for (i = 0; i < 30; i++)
{
    pCar[i] = &c[i];
}


for (i = 0; i < 30; i++)
{
    printf("Value of pCar[%d] = %s\n", i, pCar[i]);   
}
1
  • 1
    Have a look at strtok. Commented Apr 23, 2015 at 22:19

1 Answer 1

1

As suggested by @JoeFarrell, you can do it using strtok():

char c[] = "HELLO MY NAME";

char *pCar[30]; // this is an array of char pointers
int n = 0; // this will count number of elements in pCar
char *tok = strtok(c, " "); // this will return first token with delimiter " "
while (tok != NULL && n < 30)
{
  pCar[n++] = tok;
  tok = strtok(NULL, " "); // this will return next token with delimiter " "
}

for (i = 0; i < n; i++)
{
  printf("Value of pCar[%d] = %s\n", i, pCar[i]);   
}

http://ideone.com/HxfXpW

What strtok() does is it replaces de delimiters in your original string with a null-character ('\0'), that marks the end of a string. So, at the end you get:

c ─── ▶ "HELLO\0MY\0NAME";
         ▲      ▲   ▲
         │      │   │
pCar[0] ─┘      │   │
pCar[1] ────────┘   │
pCar[2] ────────────┘
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Helped a lot. Now if were to do the opposite and take that pCar stuff and put it back into the c array in the same way it was set up initially. How would I do that?
@Ashleyy, hint: you can use strcat()

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.