将char数组转换为C中的char指针

时间:2015-04-23 22:14:53

标签: c

所以我有一个char数组c,它有这样的字符:"你好我的名字"

我想创建一个char指针数组,* pCar,这样pCar [0]将拥有HELLO,而pCar [1]将拥有MY,而pCar [2]将具有NAME。

我有类似的东西,但它不起作用。

 allowed_query_verbs = ["attack","defend","armor","magic"]
 queries = dict(
    "SELECT user_name, {0}, {0}_exp FROM highscores_skills ORDER BY {0}_exp DESC".format(v) for v in allowed_query_verbs
 )
 cursor.execute(queries[skill])

1 个答案:

答案 0 :(得分:1)

根据@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

strtok()的作用是将原始字符串中的de delimiters替换为空字符('\0'),用于标记字符串的结尾。所以,最后你得到:

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