ç追加的char为char * [英] C appending char to char*

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

问题描述

所以我想追加一个字符的char *

例如我有的char *文字=;
我也有字符CH ='X';

追加(文字,CH); 使用这种方法。

void append(char* s, char c)
{

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

它给了我一个分段错误,我明白为什么我想。因为 S [LEN] 为出界。我该如何使它所以它的工作原理?我需要清除的char * 大量的为好,如果我使用的东西,比如CHAR字[500];我将如何清除一旦追加到它的一些字符?请问的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.

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

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