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

Linux kernal map

21/03/2009 – 10:46

Linux is a facinating OS but not always transparant to everybody, certainly the kernel has that problem. This linux map will help you figure out the linux kernel and has ...

CodeIgniter the views and .htaccess

14/03/2009 – 21:23

I must admit that I not a huge fan of Frameworks and Patterns because: A) They make things complicated B) Subject you to some nasty code stuff and rules C) Because templating and ...

MVC again

09/03/2009 – 22:49

I've grew bored of having to deal with some irritating PHP issues so I've turned my back to those and began testing codeIgniter. It seems strait forward but templating already ...

PHP app installer

09/02/2009 – 23:41

The last 2 to 3 days I've been working on a system that can be easely integrated into any application so that it can install itself on a server. I've ...

News paper online 1981

01/02/2009 – 23:18

This is fun, the first "domestic" use of the internet on a tv broadcast: Youtube

Mail to who?

29/01/2009 – 10:28

What's annoyin on the net is that if someone wants to mail you mail, he must know your address but  whit whspr it's history. Check it out better then disposable ...

history of the internet

29/01/2009 – 10:23

A short version of how the internet was created, the basic fundamentals. It's funny to see.

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 :