Showing posts with label C language. Show all posts
Showing posts with label C language. Show all posts

Thursday, August 1, 2013

Basics of Function Pointers in C

A good article about Basics of Function Pointers in C by Dennis Kubes can be found in his website denniskubes.com

"This post is very detailed because I am attempting to create a mental model to help beginners understand the syntax and basics of function pointers. If you are ok with detail happy reading.

Function pointers are an interesting and powerful tool but their syntax can be a little confusing. This post will going into C function pointers from the basics to simple usage to some quirks about function names and addresses. In the end it will give you an easy way to think about function pointers so their usage is more clear."

... in which I found a link to Steve Friedl's Unixwiz.net Tech Tips - Reading C type declarations

Friday, August 10, 2012

Recursive Functions


Recursive functions

Recursive functions are functions that call themselves. Several problems are naturaly defined recursively. Those problems may be solved by using recursive functions.

Example: Factorial of a positive integer number.
0! = 1
1! = 1
n! = n * (n-1)! , if n > 1

int factorial(int val){
if(val <= 1)  //stop condition.
return 1;
else
return val * factorial(val-1);  //recursive call.
}

Stop condition: Condition to stop recursive calling and return. Written before recursive calling.
Recursive calling: The problem to solve should be simpler than the previous problem. The recursive calling ends at stop condition.

Advantages: compact code, easier to write and understand.
Disadvantages: intensive stack usage, recursive functions aren't faster than equivalent non recursive functions.

Some usage examples: String manipulation, linked list operations, binary tree operations.

Example: Count number of characters in a string.

int count(char *st)
{
if(*st == '\0')
return 0;
else
return 1+conut(st+1);
}

Example: reverse a string.

void puts_inv(char *st)
{
if(*st == '\0')
return;
else
{
puts_inv(st+1);
putchar(*st);
}
}



Examples of incorrect recursive functions:

long int factorial(long int val)
{
return val * factorial(val-1);
if(val <= 1) return 1;
}

long int factorial(long int val)
{
if(val <= 1) return 1;
else return val * factorial(val);
}

long int factorial(long int val)
{
if(val <= 1) return 1;
else return val * factorial(val+1);
}

C function for getting user input


C function for getting user input.
Reads up to uinput-1 characters from stdin to uinput, removes \n adn adds \0. 
Returns number of characters of uinput.

int getUserInput(char *uinput, int size){

size_t last;

fgets(uinput, size, stdin);

if (strlen(uinput) > 0){
last = strlen(uinput) - 1;
if (uinput[last] == '\n'){ //if last char is \n replace with \0
uinput[last] = '\0';
} else {
//no \n in buffer, discard additional characters.
fscanf (stdin, "%*[^\n]"); 
(void) fgetc (stdin); // discard \n
}
}
return strlen(uinput);
}