创建一个gets函数,使用getchar函数返回返回的char *

问题描述 投票:-2回答:2

我有一段时间有这个问题。我无法创建一个允许用户使用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

c gets
2个回答
0
投票

以下是对您尝试做的事情的有根据的猜测。它包括一些解释和一个调用示例:

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;
}

1
投票

更改

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");}

所做的更改是:

  1. 您已创建指针,但尚未分配任何内存。因此,malloc声明。
  2. 对于32位编译器,sizeof(b)将永远是4。你需要i给出的数组索引。
  3. 与2相同。

这些是您需要进行的基本更改,而不会对您的逻辑进行任何更改。

© www.soinside.com 2019 - 2024. All rights reserved.