c语言子函数返回字符串的正确方式

c语言子函数返回字符串的错误

最近做leetcode上的一道题,通过子函数返回字符串。开始时用局部变量的字符串返回的,认为返回了字符串的首地址,便可以get到这个字符串,但由于局部变量离开函数后被回收了,因此字符串首地址是收到了,但是所在内容却被回收,因此出错。

//这是出错代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* intToRoman(int num) {
	int base[13] = { 1000,900,500,400,100,90,50,40,10,9,5,4,1 };
	char * basestr[13] = { "M","CM","D","DM","C","XC","L","XL","X","IX","V","IV","I" };
	int count[13];
	for (int i = 0; i < 13; i++) {
		count[i] = num / base[i];
		num -= base[i] * count[i];
	}
	char s[100];//这样子是局部变量
	int index = 0;
	for (int i = 0; i < 13; i++) {
		for (int j = 0; j < count[i]; j++) {
			strcpy(s + index, basestr[i]);
			index += strlen(basestr[i]);
		}
	}
	s[index] = '\0';
	return s;
}
int main() {
	printf("%s",intToRoman(3));
}

正确做法

法一:通过malloc函数分配
因为malloc函数分配内存在堆区,运行过程中由程序员自己管理,系统不回收。

char* intToRoman(int num) {
	int base[13] = { 1000,900,500,400,100,90,50,40,10,9,5,4,1 };
	char * basestr[13] = { "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" };
	int count[13];
	for (int i = 0; i < 13; i++) {
		count[i] = num / base[i];
		num -= base[i] * count[i];
	}
	char *s=(char*)malloc(sizeof(char)*100);
	int index = 0;
	for (int i = 0; i < 13; i++) {
		for (int j = 0; j < count[i]; j++) {
			strcpy(s + index, basestr[i]);
			index += strlen(basestr[i]);
		}
	}
	s[index] = '\0';
	return s;
}

法二:
通过引用传递(或者说传指针)
法三:
全局变量(不推荐)

猜你喜欢

转载自blog.csdn.net/qq_40836518/article/details/89164626