C语言 C 将 char 附加到 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12939370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:07:51  来源:igfitidea点击:

C appending char to char*

cstringcharsegmentation-faultappend

提问by Man Person

So I'm trying to append a charto a char*.

所以我试图将 a 附加char到 a char*

For example I have char *word = " ";I also have char ch = 'x';

例如我有char *word = " ";我也有char ch = 'x';

I do append(word, ch);Using this method..

我做append(word, ch);使用这种方法..

void append(char* s, char c)
{

    int len = strlen(s);
    s[len] = c;
    s[len+1] = '
//returns 1 if failed, 0 if succeeded 
int  append(char*s, size_t size, char c) {
     if(strlen(s) + 1 >= size) {
          return 1;
     }
     int len = strlen(s);
     s[len] = c;
     s[len+1] = '
char *append(const char *s, char c) {
    int len = strlen(s);
    char buf[len+2];
    strcpy(buf, s);
    buf[len] = c;
    buf[len + 1] = 0;
    return strdup(buf);
}
'; return 0; }
'; }

It gives me a segmentation fault, and I understand why I suppose. Because s[len]is out of bounds. How do I make it so it works? I need to clear the char*a lot as well, if I were to use something like char word[500]; How would I clear that once it has some characters appended to it? Would the strlenof it always be 500? Thanks in advance.

它给了我一个分段错误,我明白我为什么这么想。因为s[len]越界了。我如何使它起作用?char*如果我要使用像 char word[500]; 这样的东西,我也需要清除很多东西。一旦附加了一些字符,我将如何清除它?请问strlen它永远是500?提前致谢。

回答by djechlin

Typical C practice would be like:

典型的 C 实践是这样的:

append("foo", 'X');

When passing a function an array to modify the function has no idea at compile time how much space it has. Usual practice in C is to also pass the length of the array, and the function will trust this bound and fail if it can't do its work in the space it has. Another option is to reallocate and return the new array, you would need to return char*or take char**as an input but you must think carefully of how to manage heap memory in this situation. But without reallocating, yes, your function must somehowfail if it is asked to append when there is no space left, it's up for you for how to fail.

传递函数时,要修改函数的数组在编译时不知道它有多少空间。C 中通常的做法是也传递数组的长度,如果函数不能在它拥有的空间中完成它的工作,则该函数将信任此边界并失败。另一种选择是重新分配并返回新数组,您需要返回char*char**作为输入,但您必须仔细考虑在这种情况下如何管理堆内存。但是如果没有重新分配,是的,如果在没有剩余空间时要求它追加,您的函数必须以某种方式失败,这取决于您如何失败。

回答by Keith Randall

It is hard to append to a string in-place in C. Try something like this:

很难在 C 中就地附加到字符串。尝试这样的事情:

char *append(const char *orig, char c)
{
    size_t sz = strlen(orig);
    char *str = malloc(sz + 2);
    strcpy(str, orig);
    str[sz] = c;
    str[sz + 1] = '##代码##';
    return str;
}

Be sure to deallocate the returned string when done with it.

确保在完成后释放返回的字符串。

FYI: It segfaults probably because the string you are passing is stored in read-only memory. But you're right, you are also writing off of the end (the [len+1]write, not the [len]one).

仅供参考:它出现段错误可能是因为您传递的字符串存储在只读内存中。但你是对的,你也在写下结尾([len+1]写,而不是[len]一个)。

回答by Julian

If you're passing in

如果你是路过

##代码##

it will crash, because foo is normally put in readonly storage. Even if it isn't it will overwrite something bad probably! In this case the compiler if it's kind should warn you of conversion from const char * to char * which would be a clue.

它会崩溃,因为 foo 通常放在只读存储中。即使不是,它也可能会覆盖一些不好的东西!在这种情况下,编译器应该警告您从 const char * 到 char * 的转换,这将是一个线索。

回答by Julian

Yes, the assumption you made is - almost - correct - the crash may be because you're trying to write past the bounds of the string (actually only s[strlen(s) + 1]is out of bounds, because s[strlen(s)]is still a valid location - the terminating NUL byte is stored there). But you also can't modify a string literal, because it's usually in some readonly part of the process memory. Both of these actions lead to invocation of undefined behavior, which have the potential of crashing. You can solve this problem by copying the string to a dynamically allocated storage then modifying the copy. Also, you're supposed to use const char *in the argument of your function, because char *suggests that read-only strings can't be passed in.

是的,你所做的假设 - 几乎 - 正确 - 崩溃可能是因为你试图写越过字符串的边界(实际上只是s[strlen(s) + 1]越界,因为s[strlen(s)]它仍然是一个有效的位置 - 终止 NUL 字节被存储那里)。但是您也不能修改字符串文字,因为它通常位于进程内存的某个只读部分。这两个操作都会导致调用未定义的行为,这有可能导致崩溃。您可以通过将字符串复制到动态分配的存储然后修改副本来解决此问题。此外,您应该const char *在函数的参数中使用,因为char *建议不能传入只读字符串。

##代码##

Also, don't forget to free()the returned string when it's not needed anymore.

另外,free()当不再需要返回的字符串时,不要忘记它。

回答by Tom Tanner

You can't really safely append to an arbitrary string, because firstly, string constants tend to be in read-only memory, so trying to write to them is likely to result in a segmentation fault, and secondly, you have no guarantee that if they've passed you a buffer that you haven't shot over the end of it.

您不能真正安全地附加到任意字符串,因为首先,字符串常量往往位于只读内存中,因此尝试写入它们可能会导致分段错误,其次,您无法保证如果他们给了你一个缓冲区,你还没有在它的末尾射击。

In particular, if you do char x[500];

特别是,如果你做 char x[500];

there's no guarantee that strlen(x) will return you 500. It will return you how many characters it has to count forward from the start of x before it reaches a null. It could return you 0, 1 ... 500, 501 ..., depending on what is in x.

不能保证 strlen(x) 会返回 500。它会返回从 x 开始向前计数的字符数,然后它会到达空值。它可能会返回 0, 1 ... 500, 501 ...,具体取决于 x 中的内容。

Really your only options are to call append with the size of the buffer you are appending to (so you can do something appropriate if the buffer is full), or to make append allocate a new buffer every time it is called, in which case you will need to free the buffer again of course.

实际上,您唯一的选择是使用您要附加到的缓冲区的大小调用 append(因此,如果缓冲区已满,您可以做一些适当的事情),或者在每次调用时使 append 分配一个新缓冲区,在这种情况下,您当然需要再次释放缓冲区。