C programming: dynamic keyboard allocation with pointer to pointer
Written by webscriptz on 16/04/2010 – 23:41Something I’ve written for a project I have to do for school, it’s without bugs at least on visual studio 2008.
The little story about this code:
This is a dynamic memory allocation function for text entered by the user.
You give the addresses from pointers to memory placements to the function, it only return errors by value, everything else is returned by reference (pointer to pointer).
**string is the string pointer
**cntrChar is a counter for the number for characters
**cntrChar is used in another function to verify that the chain of characters entered, is longer then 1 because ‘\n’ is also seen as character so you need more then 1 to pass that test normally but it depends on the requirements of the program created.
int keyboardInputString(char **string, int **cntrChar){
char c, *iString;
int i=0;
iString = (char*)malloc(sizeof(char));
if(iString != NULL){
do{
c = getchar();
*(iString+i)=c;
i++;
iString = (char*) realloc (iString, (i+1) * sizeof(char));
if(iString == NULL)
return 1;
}while(c != '\n');
*(iString+i-1)='\0';
*string = iString;
*cntrChar = &i;
return 0;
}
else{
return 1;
}
}
exemple:
if(strcmp(**string, "exit") && **cntrChar >1)
//your code here
| Posted in »