0

我正在尝试学习 C 并编写了一个简单的程序,该程序接受来自用户的字符串并打印它。你愿意就我的做法向我提出任何建议吗?我需要很好地学习它。所以请帮助我提高自己。这是我的代码:

//Dynamic Array Allocation
#include <stdio.h>  //this is a c code
#include <conio.h>  //for using getch()
#include <stdlib.h> //for using malloc,realloc, and free

void createACopy(char * copyTo,char * copyFrom, int length) //creates copy
{
    for(int i = 0; i < length; i++) //loof for 'length' times
    {
        copyTo[i] = copyFrom[i];
    }
}

void main()
{
    printf("Please enter a string\n");
    char inputChar; //a characted input by user
    int inputLength = 0;    //holds the length of characters input so far
    char * userInput;   //a pointer that points to the beginnning of the user input
    userInput = (char *)malloc(sizeof(char));   //dynamically assign a single character size memory to the pointer
    if (userInput == NULL)  //if malloc could not find sufficient memory
    {
       free (userInput);    //free the memory
       puts ("Error Allocating memory");    //print error message
       exit (1);    //exit the program
     }
    do{ //keep looping till the user hits 'Enter' key
    inputChar = getch();    //get the character keyed in by user in inputChar variable
    if(inputChar ==char(8)) //if user hits backspace
    {
        inputLength--;  //decrease the length of user input by 1
        continue;   //continue and look for next character
    }
    char * storeOldInputHere = (char *) malloc(inputLength+1);  //dynamically find a memory location of size 'inputLenght'
    if (storeOldInputHere == NULL)  //if malloc could not find sufficient memory
    {
       free (storeOldInputHere);
       puts ("Error Allocating memory for copying the old input");
       exit (1);
     }
    createACopy(storeOldInputHere,userInput,inputLength);   //store the old Input here because realloc might give us a different location altogether.
    userInput = (char *) realloc(userInput,inputLength+2);  //now after we got a new character, reallocate memory.
    if (userInput == NULL)  //if realloc could not find sufficient memory
    {
       free (userInput);
       puts ("Error Reallocating memory");
       exit (1);
     }
    createACopy(userInput, storeOldInputHere,inputLength);  //Copy back the original input string to the newly allocated space again.
    userInput[inputLength] = inputChar; //append the new character user inserted.
    free (storeOldInputHere);   //free the storeOldInputHere
    inputLength ++; //increment the length counter by 1
    }while(inputChar != char(13));  //keep looping untill user hits 'Enter' key
    userInput[inputLength] = '\0';  //append a null charater at the end of the string
    printf("\nyou entered %d characters",inputLength);
    printf("\nyou entered: %s\n",userInput);
    free(userInput);    //free the userInput
}

提前致谢

4

1 回答 1

0

很多东西需要改进,但现在有一些建议:

首先,在 C 中逐个字符地做任何事情都是乏味且容易出错的,如果你能避免它,你应该这样做。一般来说,我更喜欢 fprintf 而不是 puts,以及 readline 或 getline 而不是 getch。

其次,在使用 malloc 时,您应该始终将它传递给您正在使用的数据类型的大小。

例如

size_t counter = 0;
//then some stuff happens in your code and counter gets set to some value...say 24
char * charspace = (char *) malloc(sizeof(char)*counter); 
// charspace is now an array with space for 24 chars.

将错误检查封装在一个函数中也是一种很好的做法,这样您就不必担心它了。

例如

void *emalloc(size_t n) {
void *p;
p = malloc(n);
if (p == NULL) {
    fprintf(stderr, "emalloc of %u bytes failed", (unsigned int) n);
    exit(1);
}
return p;
}

希望有帮助。

于 2012-08-05T22:40:13.637 回答