无法将特定字符添加到 char* 的开头,它只允许我在 C 中添加它?

Cannot add a specific character to the start of a char*, it only allows me to add it after in C?

我在用 C 语言将“-”添加到字符串开头时遇到问题,因为它会导致段错误。在字符串末尾添加“-”似乎没有问题。 本质上,该结构有两个字段,如果其中一个字段的值为“-1”,则该值意味着负数,并且“-1”将被添加到结构中的另一个字段。将 'ch' 添加到开头会导致它出现段错误。

代码如下:

        unsigned int toPrint = size(unitLiterals);
    qsort(unitLiterals->element, toPrint, sizeof(Literal*), sort);
    for (unsigned int i = 0; i < toPrint; i++){
        Literal*literal = get(unitLiterals, i);
        if (literal->isNegative == 1){
            printf("%s", literal->name);

        }
        else {
            char *ch = "-";
            strcat((char*)literal->name, ch);
            printf("%s", literal->name);
        }
        if (i != toPrint-1){
            printf(" ");
        }
        else {
            printf("\n");
        }
    }

结构初始化:

Literal *newLiteralStruct (char *name, int i){
    Literal *this = malloc(sizeof(Literal));
    this->name = name;
    this->isNegative = i; 
    return this;
}

头文件中的文字:

typedef struct Literal Literal;

struct Literal {
    char* name;
    int isNegative;
};

I would like the ch to be added at the start & not the end, and I don't know how to fix this.

不要为此使用 strcatstrcat 总是将第二个参数指向的字符串的副本附加到第一个参数指向的字符串的末尾,而不是它的开头。

您可以改为使用缓冲区和对 strcpy 的调用序列:

 char *ch = '-';                          // Note the `-` is a character, not a string.
 char buf[N];                   
 buf[0] = *ch;                            // Copy `-` to the first element of `buf`. 
 strcpy(&buf[1], literal->name);          // Copy the string in `name` to `buf`,
                                          // starting at the second element of `buf`.   
 strcpy(literal->name, buf);              // Copy the string in `buf` back to `name`.
 printf("%s", literal->name);

注意 name 必须有一个额外的元素来保存添加的 - 字符,当然还有一个元素来存储终止空字符。此外,缓冲区需要能够保存 name 中的字符串加上添加的 - 和空字符。

你也可以省略 ch 因为它不是必需的并且使代码更紧凑:

 char buf[N];
 buf[0] = '-';
 strcpy(&buf[1], literal->name);
 strcpy(literal->name, buf);
 printf("%s", literal->name);

或者你可以将name中字符串的每个字符向前排序一个元素(包括空字符),然后将'-'分配给name的第一个元素:

size_t len = strlen(literal->name);
for ( size_t i = 0; i < (len + 1); i++ )
{
    literal.name[i+1] = literal.name[i];
}
literal.name[0] = '-'; 

但是在这里,name需要能够容纳字符串+'-'+空字符。