这是我的函数。
char * substring(int begin, int end, char * string)
{
int size = end - begin + 1;
char * s = (char *)malloc (sizeof(size));
int i;
for (i = 0; i < size; i++)
{
s[i] = string[begin++];
}
return s;
}
假设我的字符串应该只是“I”。但是当我稍后尝试打印出字符串时,我得到了 I + 3 个意外的额外字符。我该如何解决这个问题?
最佳答案
首先,换行
char * s = (char *)malloc (sizeof(size));
到
char * s = malloc( size + 1 ); // + 1 for null terminator
sizeof(size)
给你一个整数的字节数(2 到 4 到 8 取决于你的平台),这不一定是你想要的。
接下来,使用strncpy
函数复制string
的前size
个字符:
strncpy( s, string, size );
确保字符串以 null 结尾:
s[size] = '\0';
关于C:如何为字符串分配准确数量的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506677/