如何连接指针数组? [英] How to concatenate pointer arrays?

查看:142
本文介绍了如何连接指针数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  串联字符数组用C

如何连接:

char *a="abcd";
char *b="1234";

使用的

的strcat()?当用户输入回答同样的* a和* B?

using the strcat()? And answer to the same when user enters *a and *b?

修改错过了这一点:不使用另一个阵列

EDIT missed out this: without using another array.

推荐答案

您不能与你已经初始化字符串猴子各地 - 他们坐在存储兼地方;不能/不应该被重写。

You can't monkey around with the string literals you've already initialized - they're sitting somewhere in memory & can't/shouldn't be rewritten.

如果你不希望其他静态定义的数组,但不介意动态分配,code以下可以完成你在找什么:

If you don't want another statically-defined array but don't mind dynamic allocation, the code below may accomplish what you're looking for:

char *a = "abcd";
char *b = "1234";
char *out;

if((out = (char *)malloc(strlen(a) + strlen(b) + 1)) != NULL)
{
   strcpy(out, a);
   strcat(out, b);
}
else
{
   //you don't have enough memory, handle it
}

如果这仍然不能接受,可以考虑不同的方法来初始化您的字符串。

If that's still unacceptable, consider a different approach to initializing your string literals.

这篇关于如何连接指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆