c - 合并指针字符串时所需的指针操作数

标签 c

我正在尝试将字符串 2 连接到字符串 1 后面,然后将该字符串分配给最终字符串。所有这些字符串都作为指针传递到函数中。当我将最终字符串指针设置为两个字符串时,出现错误。

我的预期输入/输出:

concat("string", 10, "hello", "world");
--> char *final should be: helloworld

我的连接函数:

void concat(char *final, size_t max, const char *first, const char *second)
{
    //final holds first+second
    //max is the size of first and second strings combined
    //first and second are strings

    while (*first != '\0') {
        first++;
    }
    while (*second != '\0') {
        *first = *second;
        first++;
        second++;
    }
    *first = '\0';
    *final[max] = *first;    // Error on this line
}

我的错误(第 15 行):

Indirection requires pointer operand ('int' invalid)

编辑: 可以删除 const 以避免只读变量赋值错误。

最佳答案

final 是指向 char 的指针。 final[max] 是相对于 final 位于 max 位置的字符。它实际上包含一个 * 操作,因此您不需要它。在 *final[max] = *first; 中,不需要第一个 *

事实上,final[max]被定义为*(final + max),意思是取指针final,调整它由 max 元素组成,然后引用该位置的 char*final[max] 将是 **(final + max),这不是您想要的。

尚不清楚您打算使用 final[max] = *first; 实现什么目的。此时,first 指向您刚刚写入的'\0',因此final[max] = *first;会将 final[max] 设置为 '\0'

关于c - 合并指针字符串时所需的指针操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395011/

相关文章:

c - 原子调度

c - 变量 'ch' 周围的堆栈已损坏

c - 将 float 输入到仅处理整数的程序中

c - 故障,原因不明

c - 如何将 float 转换或转换为它的位序列,例如长整型

c - 在 C 中哪里格式化/放置 "{"?

c - 如何用C语言创建临时文本文件

c - 如何测量 Linux 上 C 语言的执行时间

c - c中的逻辑门模拟

c - 读取txt,使用链表计算每个字母表