【问题标题】:strcat incompatible types error in CC中的strcat不兼容类型错误
【发布时间】:2012-08-26 15:26:57
【问题描述】:

我有一个arr[][] 形式的二维字符数组。我需要在该数组的末尾添加一个字符,有时在该数组的第 i 行或第 j 行的开头添加一个字符。这是代码sn-p:

 arr[j] = strcat(arr[j],")");
 arr[i] = strcat("(",arr[i]);

当我编译代码时,我收到错误:赋值中的类型不兼容。现在我假设arr[j]arr[i] 是字符串。我哪里错了?换句话说,在字符串开头追加或添加字符的最佳做法是什么?

【问题讨论】:

  • 你必须注意char *arr[](案例1)和char arr[][](案例2)在C语言中是两个不同的东西。在第一种情况下(&对于你的第一种情况) ,连接将发生在arr[final_position][final_position] 的末尾,但在这里的第二种情况下,它将发生在arr[j][final_position] 的末尾。在这里,在案例 1 中,它是一个指针数组,在案例 2 中,它是一个二维数组。因此,在情况 2 中,字符串连续性将在('\0' 出现)最后结束,因为分配的内存对于二维数组中的所有字符串都是连续的。

标签: c string strcat incompatibletypeerror


【解决方案1】:

首先,您不能将strcat 返回的char * 分配给现有的数组行。

但更重要的是,strcat 不会为连接结果分配新字符串,而是在第一个字符串中就地执行连接。返回值始终是第一个字符串,只是为了方便。因此,在第一种情况下,您只需:

strcat(arr[j],")");

(假设arr[j] 对于添加的字符足够大)

第二种情况更复杂,因为您必须将) 添加到现有字符串的开头。你可以例如在单独的缓冲区中执行操作,然后使用strcpy 将其复制回arr[j],或者将字符串的整个内容向前移动一个字符并手动添加括号:

memmove(arr[j]+1, arr[j], strlen(arr[j]));
arr[j][0]='(';

从你的错误中我担心你认为char * 就像其他语言中的字符串类,但可惜不是那样的。请记住,在 C 语言中字符串只是哑字符数组,不要指望像高级语言那样有任何花哨的商品。

【讨论】:

  • 感谢您澄清了我对 Matteo 的怀疑。如果我很贪婪,请原谅我,但是有没有更短的方法可以在字符串的开头添加一个字符? :P 我的意思是,如果我们将每个字符移动 1 位或将所有字符复制到单独的字符串中,我可以猜测它的效率为 O(n)。
  • 代码更短还是效率更高?无论如何,我认为你不能短于两行(但你可以封装处理一般情况的in a function),并且由于字符串是向量,你不能击败 O(N) 进行插入一开始。
【解决方案2】:

Pl。看看下面的简单示例是否有帮助,

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char* argv[])
{
    char myarray[2][10], *temp;

    //Populating something in the array
    strcpy(myarray[0], "string1");
    strcpy(myarray[1], "string2");
    printf("%s\n", myarray[0]);
    printf("%s\n", myarray[1]);

    //Adding something at the end of the string..
    //Be careful to check if the source is large enough.
    //Also consider using strncat
    strcat(myarray[0], ")");
    printf("Appended at the end %s\n", myarray[0]);

    //Append at the beginning
    //Here you can use a temporary storage.
    //And pl. do the required error handling for insufficent space.
    temp = malloc(strlen(myarray[1]) + strlen("(") +1);
    strcat(temp, "(");
    strcat(temp, myarray[1]);
    strcpy(myarray[1], temp);
    printf("Appended at the beginning  %s\n", myarray[1]);
    free(temp);
    return 0;
}

【讨论】:

  • 你忘了free(temp);另外,请记住,使用malloc 进行分配比就地移动字符串要慢得多。
  • @MatteoItalia,感谢 Matteo。我添加了free(temp)
猜你喜欢
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多