最近在学习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出来的堆空间才行
改成用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;
}