我怎样才能在我的 C 字符串前面插入一个字符?

how can i insert a single char in front of my c string?

所以在第 28 行,我创建了一个名为 temp 的 C 字符串。我将 temp[0] 的值分配给 string[index] 的值。现在我想将字符串添加到 temp 的末尾,然后使字符串存储与 temp 相同的值。我尝试使用 strcat(),但它给了我一个 "buffer overflow detected"。有没有我可以尝试的任何其他解决方案,基本上我想要的只是 "string = string[index] + string" 如果在 C 中是可能的。我需要程序以一定的速度 运行 所以我不想使用循环解决这个问题。

//Problem        : Expecto Palindronum
//Language       : C
//Compiled Using : GCC
//Version        : GCC 4.9.1
//Input for your program will be provided from STDIN
//Print out all output from your program to STDOUT

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

int main() {
    char string[202];
    char revstring[202];
    gets(string);
    int ilength = strlen(string);
    int index = ilength - 1;
    int i;
    for(i = 0; i<(ilength);i++){
        int y =  index - i;
        revstring[i] = string[y];
    }
    while(1==1){
        int length = strlen(string);
        if(strcmp(revstring,string)==0){
            printf("%d",length);
            break;
        }else{
            char temp[202];
            int y;
            temp[0] = string[index];
            strcat(temp,string); //gives me buffer overflow, any solution to this?
            //for(y = 0; y < (length); y++){  //my failed loop
                //temp[y+1] = string[y];
            //}
            int ind = length - index - 1;
            revstring[length] = revstring[ind];
            memcpy(string,temp,202);
        }
    }
    return 0;
}

您的代码有很多问题。我将只解决您关于缓冲区溢出(段错误)的问题。

来自 man strcat:

strcat() 函数将 src 字符串附加到 dest 字符串,覆盖 dest 末尾的终止空字节 ('\0'),然后添加终止空字节。

但是您在 dest 的末尾没有终止空字节。要解决眼前的问题:

temp[0] = string[index];
temp[1] = 0;

我还应该提到什么?

从人那里得到:

错误:切勿使用 gets()。因为在事先不知道数据的情况下无法判断 gets() 将读取多少个字符,并且因为 gets() 将继续存储超过缓冲区末尾的字符,所以使用它是极其危险的。它已被用来破坏计算机安全。请改用 fgets()。

了解以空字符结尾的字符串。