C programming: dynamic keyboard allocation with pointer to pointer

Written by webscriptz on 16/04/2010 – 23:41

Something 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

Windows ate my thumbdrive

02/04/2010 – 09:00

Yesterday was disappointing and frustrating. Visual studio freaked out which resulted in my project becoming inaccessible from my thumb drive and not long after that the partition table was destroyed, resulting ...

Yii themes

25/02/2010 – 18:57

This was actually fun, a first, i have to admit. Normally when i do convert a template to a theme, i is time consuming, in Yii after some rudamentry settings ...

Annoyed…with coding

22/02/2010 – 00:39

I've been coding away all week, that is between my other jobs at home :P In all my 'wisdom' and persistence i made a small app with Yii which stores data ...

YII framework configuration

20/12/2009 – 23:47

I'm toying with the Yii Framework for some time now and even if i cost me a lot of anger and frustration in the beginning I'm starting to like it ...

2012: a parody at the end

11/11/2009 – 23:51

Delicious.com served this last thing and unfortunately i can't keep my skepticism to myself;  please read it first, it really collects two point of views and all the events concerning. It's ...

Register & Yii projects

24/09/2009 – 23:09

So, I think ti's time for some updates on the website. I has been a bit wild the last 3 weeks. School has started yet again and I had a project ...

About Me

Here I'll share my knowledge, discovery and experience related to my hobby and work. Most articles on this site are related to blog design, short reviews, tips and make money online. More

Find entries :