@关于C语言函数返回char *类型的一些问题TOC
关于C语言函数返回char *类型的一些问题
以下是我在写C语言中返回值类型为char *函数时遇到的一些问题,在参考了博客:https://blog.csdn.net/Xixo0628/article/details/119870914后修改代码可成功运行。
题目
输入一个字符串,然后输入两个字符,输出该字符串中从第一个字符匹配的位置到第二个字符匹配的位置的所有字符。通过返回字符指针的子函数实现。(从字符串的开头搜索第一个字符,同时从字符串的末尾查找第二个字符。)输入:programming r g,输出:rogramming。
原代码
#include <stdio.h>
#include <string.h>
char* subString(char str[50], char a, char b){
int i = 0, j = 0, count1 = 0, count2 = 0;
char *newstr;
while(str[i] != '\0'){
if(str[i] == a){
count1++;
}
if(str[i] == b){
count2++;
}
if(count1>=1 && count2<=2){
newstr[j] = str[i];
j++;
}
i++;
}
newstr[j] = '\0';
return newstr;
}
int main(){
char str[50];
printf("Enter a string:");
gets(str);
char* res = NULL;
printf("Enter two char:");
char a,b;
scanf("%c %c",&a,&b);
res = subString(str,a,b);
printf("%s",res);
return 0;
}
运行结果
很奇怪,返回值不为0,无结果输出
修改后的代码
char* subString(char str[50], char a, char b){
int i = 0, j = 0, count1 = 0, count2 = 0;
//此处添加了malloc
char *newstr = (char *)malloc(sizeof(char));
while(str[i] != '\0'){
if(str[i] == a){
count1++;
}
if(str[i] == b){
count2++;
}
if(count1>=1 && count2<=2){
newstr[j] = str[i];
j++;
}
i++;
}
newstr[j] = '\0';
return newstr;
}
运行结果
成功!
分析原因
当函数返回作为数组名的newstr之后,临时字符数组的空间就会被释放。之后又重新调用了新的函数printf,导致最终根据返回指针所输出的结果变成了刷新后的值,而这个值几乎可以认为是随机的。