C 将 char 附加到 char* [英] C appending char to char*

查看:53
本文介绍了C 将 char 附加到 char*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

void append(char* s, char c)
{

    int len = strlen(s);
    s[len] = c;
    s[len+1] = '\0';
}

它给了我一个分段错误,我明白我为什么这么想.因为 s[len] 越界了.我如何使它起作用?如果我要使用 char word[500]; 之类的东西,我还需要大量清除 char*;一旦附加了一些字符,我将如何清除它?它的 strlen 是否总是 500?提前致谢.

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 strlen of it always be 500? Thanks in advance.

推荐答案

典型的 C 实践如下:

Typical C practice would be like:

//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] = '\0';
     return 0;
}

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

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 somehow fail if it is asked to append when there is no space left, it's up for you for how to fail.

这篇关于C 将 char 附加到 char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆