学习动态分配

时间:2012-08-05 22:21:34

标签: dynamic

我正在尝试学习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
}

先谢谢

1 个答案:

答案 0 :(得分:0)

需要改进的东西很多,但现在有几点建议:

首先,在C char-by-char中执行任何操作都很繁琐且容易出错,如果可以避免,则应该这样做。一般来说,我更喜欢fprintf to puts,和readline或getline over getch。

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

e.g。

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.

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

e.g。

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

希望有所帮助。