【发布时间】:2020-12-22 22:56:45
【问题描述】:
我正在尝试在 C 中创建子字符串函数,这非常合乎逻辑且容易,但由于某种原因它会打印出符号。我在网上查了很多次,对比其他人的功能,但我找不到我的代码不起作用的确切原因。
#define MAX 50
char* substring(char string[], int indexBeginning, int indexEnd) {
const char *result[MAX];
int n= 0;
for (int i = indexBeginning; i <= indexEnd; i++) {
result[n++] = string[i];
}
result[n] = '\0';
return result;
}
【问题讨论】:
-
resultis 1) 类型不正确(应该是char []) 2) 是本地的,无法返回 -
malloc- 是的,const- 没有。是什么让你如此相信? -
result[n++] = string[i]将char值(提升为int)分配给char *指针对象。这需要诊断。result是指针数组,而不是字符数组。 -
请打开编译器警告,看看这段代码有什么问题。
-
@JustCaused 我认为你混淆了
const和static。使用声明static char result[MAX],您可以return result;。但是每次调用该函数时,旧的result都会被覆盖。
标签: c substring c-strings function-definition