c - strcat 错误

标签 c arrays string strcat

以下是我的代码的一部分。该代码在数组 listL 中查找具有相同值的项目组。我希望只需要 main() 就可以理解。

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

void append(char* s, char c)
{
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}

int leftSame(int listL[4][4][2], int i, int j){
    if(j==0){
        return 0;
    }
    if(listL[i][j][0]==listL[i][j-1][0]){
        return 1;
    }
    return 0;

}

int topSame(int listL[4][4][2], int i, int j){
    if(i==0){
        return 0;
    }
    if(listL[i][j][0]==listL[i-1][j][0]){
        return 1;
    }
    return 0;

}
int realIndex(char group[64][256],int a){
    while (strlen(group[a])<3){
        a = atoi(group[a]);
    }
    return a;
}
int main(void)
{
    int listL[4][4][2]= {{{0, 0}, {0, 0}, {0, 0}, {1, 0}},{{0, 0}, {0, 0}, {1, 0}, {0, 0}},{{0, 0}, {0, 0}, {0, 0}, {1, 0}},{{0, 0}, {0, 0}, {1, 0}, {1, 0}}};
    char group[64][256];
    int count = 0;
    size_t i,j;
    char snum[256];
    int leftIndex=0;
    int topIndex=0;
    int a=0;
    int A=0;
    int B=0;
    for (i = 0; i < 64; i++){
        memset(group[i], 0, 256 + 1);// zero all memory in the list
    }

    for(i=0;i<sizeof(listL)/sizeof(listL[0]);i++){
        for(j=0;j<sizeof(listL)/sizeof(listL[0]);j++){
            A= leftSame(listL,i,j);
            B=topSame(listL,i,j);
            if(A && B){
                leftIndex=realIndex(group,listL[i][j-1][1]);
                topIndex=realIndex(group,listL[i-1][j][1]);
                if (topIndex==leftIndex){
                    sprintf(snum, "%d", i);
                    strcat(group[leftIndex],snum);
                    strcat(group[leftIndex],'_');
                    sprintf(snum, "%d", j);
                    strcat(group[leftIndex],snum);
                    strcat(group[leftIndex],'_');
                    listL[i][j][1]=leftIndex;
                }
            }
        }

    }
        return 0;




}

每次使用 strcat 时,我都会收到错误“传递‘strcat’的参数 2 使指针来自整数而不进行强制转换”。当我将 snum 定义为 sum[256] 时,是否没有考虑到强制转换?这是什么意思以及如何解决它?

我想要做的是将字符串“i_j_”附加到组[leftIndex]中的项目。

最佳答案

您将字 rune 字(包含在 ' 中)作为第二个参数传递给某些 strcat,例如

strcat(group[leftIndex],'_');

但是 strcat 期望第二个参数(及其第一个参数)为 char* 类型,而不是 char 类型,并且两者都为它们需要以 NUL 结尾。这就是提示者提示的原因。

使用字符串文字而不是字 rune 字来解决问题:

strcat(group[leftIndex],"_");
<小时/>
memset(group[i], 0, 256 + 1);

有一个差一错误。使用

memset(group[i], 0, 256);

或更好

memset(group[i], 0, sizeof(group[i]))

关于c - strcat 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286399/

相关文章:

javascript - 无法从服务器端获取数组

c - 数组中的类型转换

python - 如何使用 python/pandas 根据一列中的字符串拆分和复制行?

Ruby 风格提示 : Avoid eval, 并保持清晰有序

python - 每 n 个单词将字符串拆分为更小的字符串

java - Java 中关于获取子字符串的 IndexOutOfBoundsException

c - C语言中的感叹号是什么意思?

c - 不同类型的链表!

c - 这段代码有什么问题? Eventhe printf 没有被打印出来

c - 在终端中隔离标准输入和标准输出