为什么输出乱码

C语言 码拜 8年前 (2016-06-10) 1157次浏览
最近在学习C语言,想知道下面代码为什么会输出乱码。

#include "stdafx.h"
char* getLine() {
	int c;
	char a[20];
	int index=0;
	while ((c = getchar())!="\n") {
		a[index++] = c;
	}
	a[index] = "\0";
	return a;
}
int main()
{
	printf("%s", getLine());
	while (true) {}
    return 0;
}
解决方案

80

你返回的是一个在栈上分配的数组首地址(getLine调用结束该数组生命周期就结束了)
改成用malloc出来的堆空间才行

#include<stdio.h>
#include<stdlib.h>
char* getLine() {
	int c;
	char *a = (char *)malloc(20);
	int index = 0;
	while ((c = getchar()) != "\n") {
		a[index++] = c;
	}
	a[index] = "\0";
	return a;
}
int main()
{
	printf("%s", getLine());
	while (true) {}
	return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明为什么输出乱码
喜欢 (0)
[1034331897@qq.com]
分享 (0)