我有一段时间有这个问题。我无法创建一个允许用户使用get_char()函数获取char *的gets(int maxChar)函数。
我目前的代码:
char* gets(int maxChar) {
char a;
char* b;
int i;
for(i = 0; i<maxChar; i = i + 1){
a = getchar();
if (a != 0x0D) {putchar(a);} else {puts("\r\n");break;}
b[sizeof(b)] = a;
}
if (sizeof(b) > maxChar-1) {puts("\r\n");}
return b;
//if (b[sizeof(b)-1] != '')
}
get_char()函数完美地运行。
完整kernel.c:https://pastebin.com/3bqTbHsv
以下是对您尝试做的事情的有根据的猜测。它包括一些解释和一个调用示例:
char* _gets(int maxChar) // change name to avoid conflict with library 'gets'
{
//char a; //addresses concern pointed out in comments.
int a; //variable is used by function that can return EOF (-1)
int i=0; //
char* b = calloc(maxChar + 1, 1);//point pointer to memory (that it owns)
if(b) //test for success before going on
{
for(i = 0; i<maxChar-3; i = i + 1) // -3 to leave room for \r\n\0
{
a = getchar();
if ((a != 0x0D) && (a != EOF))
{
putchar(a);
b[i]=a;// place char into string accumulator
}
else break;// either EOF or <ENTER> occurred
} // no need for else in this implementation as we can handle
// the clean up once the conditions are met by outputting
// user's entries, then preparing your string (array) for return
puts("\r\n");
b[i++]='\r';
b[i++]='\n';
b[i++]='\0';
}
else return NULL;//failed to allocate memory. leave
return b; // return b (now a string)
//if (b[sizeof(b)-1] != '') // not sure what this was for
}
int main(void)
{
char *strArray = _gets(10);//creates memory for strArray
if(strArray) //use only if not NULL
{
printf("The array contains: %s", strArray );
free(strArray );
}
return 0;
}
更改
char* b;
至
char* b = (char *)malloc(maxChar);
和
b[sizeof(b)] = a;
至
b[i] = a;
另外,改变
if (sizeof(b) > maxChar-1) {puts("\r\n");}
至
if (i > maxChar-1) {puts("\r\n");}
所做的更改是:
malloc
声明。sizeof(b)
将永远是4
。你需要i
给出的数组索引。这些是您需要进行的基本更改,而不会对您的逻辑进行任何更改。