简体   繁体   English

在C语言中将char数组转换为char指针

[英]Convert a char array to char pointer in C

So I have a char array, c, which has characters like this: "HELLO MY NAME" 所以我有一个char数组c,它的字符如下:“ 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. 我想创建一个char指针数组* pCar,以便pCar [0]将具有HELLO,而pCar [1]将具有MY,而pCar [2]将具有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]);   
}

As suggested by @JoeFarrell, you can do it using strtok() : 正如@JoeFarrell所建议的那样,您可以使用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 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. strtok()作用是用一个空字符( '\\0' )替换原始字符串中的定界符,该字符用于标记字符串的结尾。 So, at the end you get: 因此,最终您将获得:

c ─── ▶ "HELLO\0MY\0NAME";
         ▲      ▲   ▲
         │      │   │
pCar[0] ─┘      │   │
pCar[1] ────────┘   │
pCar[2] ────────────┘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM