Ashleyy
Ashleyy

Reputation: 15

Convert a char array to char pointer in C

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]);   
}

Upvotes: 0

Views: 1639

Answers (1)

ericbn
ericbn

Reputation: 10948

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] ────────────┘

Upvotes: 1

Related Questions