我正在创建这个函数,它从一个更大的字符串中提取一个单词或字符串的一部分,它工作得很好,但我必须使用 strcpy 将它从指针转换为数组,是否可以返回一个数组?
如果不可能,我可以直接使用指针吗?我的意思是,使用指针而不是数组会导致标题 <string.h> 函数出现问题?或者我可以毫无问题地使用 alla 功能?
#include <stdio.h>
#include <string.h>
char *substr(const char mainstring[], const int cstart, const int clength){
// printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
int main_length = 0;
int over_length = 0;
main_length = strlen(mainstring); // gets the length of mainstring[]
over_length = ( main_length - (cstart + clength)); // the value must be greater than -1 and less than the length of the mainstring[]
char *result = malloc(clength+1); // initialize by adding +1 for terminator \ 0
//That must be equal to or greater than 0 and less than the maximum length of the mainstring
if ( over_length >= 0 && over_length <= (cstart + clength)) {
strncpy(result, mainstring+cstart, clength); // copies the selected part to result
strcat(result, "\0"); // add terminator EOS end of string
}else{
printf("\n Error: Excessive size : %d", over_length); //shows when the condition is not met
}
return result;
}
int main(){
// use the function substr("String", start, length)
printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
return 0;
}
您不能将数组作为值返回,因为在大多数上下文中,数组会自动衰减到指向其第一个元素的指针。因此
return result;
实际上是
return &result[0];
这char*
不是char[]
。
使用 C 返回数组中的答案中描述了解决方法。特别是,用 包裹数组的那个struct
很有趣。
顺便说一句。对称地,不能将数组作为函数参数传递。
当你看到
void fun(char arr[N])
它是一个语法糖:
void fun(char *arr)
N
被忽略。
有些人认为使用数组参数是一种不好的做法。大多数情况下,因为arr
在两个上下文中都不是数组,即sizeof(arr) == sizeof(char*)
.
实际上,使用数组是很困难的:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句