将字符串数组赋给字符串指针数组

时间:2018-06-04 01:29:19

标签: c arrays string pointers

我试图将tmp变量中的字符串存储在*ans[key]变量中。在分配之后,我想清空tmp变量,获取另一个字符串,并将其添加到*ans[key+1],依此类推。

问题是,如果我清空tmp字符串,ans[key]中的值也会被清空。

int main() {

char tmp[20] = "abc";
char* ans[20] = {0};

printf ("%s\n", tmp); // shows abc
ans[0] = tmp; 
printf("%s\n", ans[0]); // shows abc
tmp[0] = 0;
printf("%s\n", ans[0]); // shows null

}

我想我错过了关于字符串数组或指针的东西。

1 个答案:

答案 0 :(得分:1)

int main()
{
  char tmp[20] = "abc";
  char *ans[20] = {0};

  printf("%s",tmp);
  ans[0] = strdup(tmp); // allocate copy of tmp on heap
  printf("%s",ans[0]);
  tmp[0]=0;
  printf("%s",ans[0]); // ans[0] not affected
}
相关问题