I've here very intersting discussion about the best and common ways to return an array from a function..
Some solutions to use output parameter and copy the value of the array into the value of this output parameter array.
Other solution to pass an array and use it inside the function.
Others to allocate the array inside the function and return refrence to it, but the caller have to free it once done.
Others to return a struct contains this pointer...
Please enjoy; stackoverflow.com/questions/8865982/return-array-from-function-in-c
Showing posts with label c. Show all posts
Showing posts with label c. Show all posts
15 January 2012
Get base, simple, non-acurate function
I've wrote a function to get a number string in some arbitrary bases.
I claim that this function is not accurate.
Here's the source code:
I claim that this function is not accurate.
Here's the source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getBase(int num, int base, char* string);
char numbers[] = {'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'};
int
main (int argc, char *argv[])
{
char str[32];
getBase(2, 2, str);
printf("%s\n", str);
getBase(255, 16, str);
printf("%s\n", str);
getBase(769878, 10, str);
printf("%s\n", str);
return 0;
}
void getBase(int n, int b, char* str)
{
const size_t SIZE = 32;
char arr[32+1]={0}; int digits=SIZE, i;
char* ptr = arr;
while (n > 0)
{
int t = n%b;
n/=b;
arr[--digits] = numbers[t];
}
while ( *ptr == '\0') ptr++;
strcpy(str, ptr);
}
12 September 2011
How to determine the amount of memory required by my char* in struct?
Suppose you have the following C struct:
1. typedef struct 2. { 3. char* name; 4. }Emp;I asked in SO on how to determine the amount of memory to allocate to the char* struct member. and the answer was to use lazy/delayed allocation as of:
1. void setName(Emp* emp, char* newName) 2. { 3. free(emp->name); 4. emp->name = malloc(strlen(newName) + 1); 5. strcpy(emp->name, newName); 6. }(It seems to me to be the same idea used for Objective-C, the setter is release the previous pointer and then retain (in C to copy) the parameter pointer. So, the whole program will be:
1. #include <stdio.h> 2. #include <string.h> 3. #include <stdlib.h> 4. 5. typedef struct 6. { 7. char* name; 8. }Emp; 9. 10. void init(Emp** emp) 11. { 12. *emp = malloc(sizeof(Emp)); 13. (*emp)->name = NULL; 14. (*emp)->name = malloc(sizeof(char*)); 15. } 16. 17. void release(Emp** emp) 18. { 19. free((*emp)->name); 20. free(*emp); 21. } 22. 23. void setName(Emp* emp, char* newName) 24. { 25. free(emp->name); 26. emp->name = malloc(strlen(newName) + 1); 27. strcpy(emp->name, newName); 28. } 29. char* getName(Emp* emp) 30. { 31. return emp->name; 32. } 33. 34. int main(void) 35. { 36. Emp* emp; 37. init(&emp); 38. setName(emp, "Muhammad Abdullah"); 39. printf("%s", getName(emp)); 40. release(&emp); 41. 42. return 0; 43. }
26 August 2011
Implemet callbacks using callback interfaces
SA,
While I am fasting now (there are about 2 hours left for the breakfast), I'd like to talk about some very important usage of interfaces...
I am here by interfaces mean the types that contains only function prototypes.
The interfaces found in many programming language like Java, C# and others.
I'll not talk about any particular programming language here, although, the code samples will be pseudocode.
Suppose We want to build some Generic function that draw a button on the screen and execute it:
Now we need to add the functionality to the button, but remember this is a generic module, so the functionality will be provided by the module user.
We can modify our code to appear like:
Now, the use can send a pointer to a function that will execute the action when the button is clicked.
The solution above can work for language that support function pointers such as C, C++ (Javascript also support passing functions as parameters, and FP langs too)
But what is the language doesn't support function pointers such as Java..
In this case, Interfaces are used and it called then, Callback interfaces...
Let's rewrite our sample:
And here's the code Clickable interface:
So The user to call the above function, it should provide an implementation for the Clickable interface and its onClick function.
Example calling the function:
While I am fasting now (there are about 2 hours left for the breakfast), I'd like to talk about some very important usage of interfaces...
I am here by interfaces mean the types that contains only function prototypes.
The interfaces found in many programming language like Java, C# and others.
I'll not talk about any particular programming language here, although, the code samples will be pseudocode.
Suppose We want to build some Generic function that draw a button on the screen and execute it:
1. 2. 3. 4. 5. 6. 7. | void drawButton(Panel container, String buttonName) { Button b = new Button(); b.setName(buttonName); container.add(b); } |
We can modify our code to appear like:
1. 2. 3. 4. 5. 6. 7. 8. | void drawButton(Panel container, String buttonName, int (*onClick) (Button b)) { Button b = new Button(); b.setName(buttonName); container.add(b); (*onClick) (b); } |
Now, the use can send a pointer to a function that will execute the action when the button is clicked.
The solution above can work for language that support function pointers such as C, C++ (Javascript also support passing functions as parameters, and FP langs too)
But what is the language doesn't support function pointers such as Java..
In this case, Interfaces are used and it called then, Callback interfaces...
Let's rewrite our sample:
1. 2. 3. 4. 5. 6. 7. 8. | Button drawButton(Panel container, String buttonName, Clickable clickable) { Button b = new Button(); b.setName(buttonName); container.add(b); clickable.onClick(b); return b; } |
1. 2. 3. 4. 5. | public interface Clickable { public void onClick(Button b); } |
So The user to call the above function, it should provide an implementation for the Clickable interface and its onClick function.
Example calling the function:
1. 2. 3. 4. 5. 6. 7. 8. 9. | drawButton(containerPanel, "Go To HomePage", new Clickable() { public void onClick(Button b) { // do the button action here. } } ); |
18 August 2011
Installing Objective-C on Linux
SA,
In a previous post we have seen how to compile and run Objective-c programs on ubuntu linux..
If we used NextSTEP framework .. we need to follow steps here :
Installing and Using GNUstep and Objective-C on Linux
a very good tutorial ..
In a previous post we have seen how to compile and run Objective-c programs on ubuntu linux..
If we used NextSTEP framework .. we need to follow steps here :
Installing and Using GNUstep and Objective-C on Linux
a very good tutorial ..
17 August 2011
Step-by-step running Objective-c on Ubuntu Linux for Windows users
SA,
In this post, I'll try to compile and run the code in this Objective-c Wikibook lesson
If you are using M$ Windows, go download VMWare Player from here and then download ubuntu Linux, I am using version 10.04.. you can get some recent version if you like..
There are variety of tutorials online to help you install ubuntu on vmware.. it is a very trivial task..
Once you have your ubuntu distribution up and running (either a VM or a standalone installation)... keep reading ...
Ubuntu linux (and almost all linux distro) come with Parts of GCC (GNU Compiler Collections) pre-installed.
Let's test the existence of a C compiler. Now type in the command line the following command:
And Then:
If you find the following output printed on the console window, then we are going in the right direction:
Now let's install the Objective-c compiler into the GCC (it is about 4MB):
Open synaptic (from command line `sudo synaptic` [will prompted for your password]
Now search for "objc" in synaptic.. and then install the package "libobjc2".
Now we are ready...
Let's try to compile and run the example in the wikibooks link we have talked about before..
First create a directory in your home directory called "objc"
and then put the three files below in it
Here's the interface Point:
(note, return to the wikibooks link if you need to understand the code)
And here's the implementation class:
And now the Test file:
Now let's compile the above program..
The easiest way to do so is to execute the following command from the same directory where these files exist (objc directory)
Note, the `-lm` is required only because we use the math.h library.
now let's execute the program:
That's all.. hope that you find this post helpful..
In this post, I'll try to compile and run the code in this Objective-c Wikibook lesson
If you are using M$ Windows, go download VMWare Player from here and then download ubuntu Linux, I am using version 10.04.. you can get some recent version if you like..
There are variety of tutorials online to help you install ubuntu on vmware.. it is a very trivial task..
Once you have your ubuntu distribution up and running (either a VM or a standalone installation)... keep reading ...
Ubuntu linux (and almost all linux distro) come with Parts of GCC (GNU Compiler Collections) pre-installed.
Let's test the existence of a C compiler. Now type in the command line the following command:
cat <<EOF>hello.c
#include<stdio.h>
int main(void){printf("In the name of Allah\n");}
EOF
And Then:
gcc -o hello hello.c && ./hello
If you find the following output printed on the console window, then we are going in the right direction:
In the name of Allah
Now let's install the Objective-c compiler into the GCC (it is about 4MB):
Open synaptic (from command line `sudo synaptic` [will prompted for your password]
Now search for "objc" in synaptic.. and then install the package "libobjc2".
Now we are ready...
Let's try to compile and run the example in the wikibooks link we have talked about before..
First create a directory in your home directory called "objc"
and then put the three files below in it
Here's the interface Point:
//Point.h #import <objc/Object.h> @interface Point : Object { @private double x; double y; } -(id) x: (double) x_value; -(double) x; -(id) y: (double) y_value; -(double) y; -(double) magnitude; @end
(note, return to the wikibooks link if you need to understand the code)
And here's the implementation class:
//Point.m #import "Point.h" #import <math.h> @implementation Point -(id) x: (double) x_value { x = x_value; return self; } -(double) x { return x; } -(id) y: (double) y_value { y = y_value; return self; } -(double) y { return y; } -(double) magnitude { return sqrt(x*x + y*y); } @end
And now the Test file:
//Test.m #import "Point.h" #import <stdio.h> int main(void) { Point *p = [[Point alloc] init]; [p x:10.0]; [p y:20.0]; printf("The Distance from Point %g to %g is %g\n", [p x], [p y], [p magnitude]); return 0; }
Now let's compile the above program..
The easiest way to do so is to execute the following command from the same directory where these files exist (objc directory)
gcc -o Test *.m -lobjc -lm
Note, the `-lm` is required only because we use the math.h library.
now let's execute the program:
./Test
The Distance from Point 10 to 20 is 22.3607
That's all.. hope that you find this post helpful..
14 August 2011
Java Native Access (JNA) by Example..
Java Native Access is a mean by which you can call native code (C/CPP) from your java programs.
It is intend is to remove the plumbing code when using JNI..
Let's write a simple example together..
First, let's write the Native (CPP) library:
" means, you can read in wikipedia about each term, but what you need to know, it is required to be included in our code to be able to export it to a DLL library)
Let's generate the DLL from the above source code:
Now we have the file "add.dll", we need to export its contents to see whether the our "add" function is being exported or not.
There's a yet simple but powerful tool called dependencywalker
.. download it and open the dll file using it. (as shown below)
Now Let's write the Java program that will call this native function ..
You will need to download the jar file of jna library..
Download it from here.
Open Eclipse and create a new Java Project and name it as "AddJNAExample".
put the file "jna.jar" and put it in the project build path in eclipse.. and come to write the source code for the program.
And Here's the Driver:
Note, If you run it now, the following exception will be thrown:
JNA involves more complex type-mappings ...
References:
http://www.cygwin.com/cygwin-ug-net/dll.html
http://today.java.net/pub/a/today/2009/05/19/protect-your-legacy-code-jna.html
http://www.dependencywalker.com/
It is intend is to remove the plumbing code when using JNI..
Let's write a simple example together..
First, let's write the Native (CPP) library:
#include <iostream> extern "C" __declspec(dllexport) int add (int x, int y) { return x + y; }(Don't ask me what this line "extern "C" __declspec(dllexport)
" means, you can read in wikipedia about each term, but what you need to know, it is required to be included in our code to be able to export it to a DLL library)
Let's generate the DLL from the above source code:
g++ -c add.cc
dir add.o
g++ -shared -o add.dll add.o
dir add.dll
Now we have the file "add.dll", we need to export its contents to see whether the our "add" function is being exported or not.
There's a yet simple but powerful tool called dependencywalker
.. download it and open the dll file using it. (as shown below)
Now Let's write the Java program that will call this native function ..
You will need to download the jar file of jna library..
Download it from here.
Open Eclipse and create a new Java Project and name it as "AddJNAExample".
put the file "jna.jar" and put it in the project build path in eclipse.. and come to write the source code for the program.
package com.daz; import com.sun.jna.Library; import com.sun.jna.Native; public interface Add extends Library { Add INSTANCE = (Add) Native.loadLibrary("add", Add.class); int add(int x, int y); }
And Here's the Driver:
package com.daz; public class Test { public static void main(String[] args) { Add lib = Add.INSTANCE; System.out.println(lib.add(10, 20)); } }
Note, If you run it now, the following exception will be thrown:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'add': The specified module could not be found.
This is because, you will need to specify the dll library to the jvm as follows:java -Djna.library.path="D:\dlls\add.dll" com.daz.Test
The result will be:30
JNA involves more complex type-mappings ...
References:
http://www.cygwin.com/cygwin-ug-net/dll.html
http://today.java.net/pub/a/today/2009/05/19/protect-your-legacy-code-jna.html
http://www.dependencywalker.com/
Never return a local pointer from a function
SA,
I am now try to write some example (will post here) on JNA (Java Native Access), so I am trying to write some simple cpp program...
While I am writing it, I've faced a problem ... And here's the story..
We always hear this phrase : "Never return a local pointer from a function"
Yes I know it good, but I usually forget it..
Here's some example that I took about 30 minutes investigate to know what's wrong!, and finally I realized this rule!:
It returns some corrupted string (GCC on Windows)
And here's the correct code:
I am now try to write some example (will post here) on JNA (Java Native Access), so I am trying to write some simple cpp program...
While I am writing it, I've faced a problem ... And here's the story..
We always hear this phrase : "Never return a local pointer from a function"
Yes I know it good, but I usually forget it..
Here's some example that I took about 30 minutes investigate to know what's wrong!, and finally I realized this rule!:
#include <iostream> #include <cstring> using namespace std; char* sayHelloFor(char*); int main(void) { char* ret = sayHelloFor("Ali"); cout << ret << endl;; return 0; } char* sayHelloFor(char* name) { char* hello = "Hello "; char str[40] = {'\0'}; // this is the local arrary/pointer strcat(str, hello); strcat(str, name); return str; }
It returns some corrupted string (GCC on Windows)
And here's the correct code:
#include <iostream> #include <cstring> using namespace std; void sayHelloFor(char*, char**); int main(void) { char c[40] = {0}; char* ret = c; sayHelloFor("Ali", &ret); cout << ret << endl;; return 0; } void sayHelloFor(char* name, char** out) { char* hello = "Hello "; //char str[40] = {'\0'}; // this is the local arrary/pointer strcat(*out, hello); strcat(*out, name); //return str; }
06 August 2011
Why C accept confusion in conditional operation while Java not
Usually, when we begun to learn Programming in C, our teachers warn us from the following Syntax:
if ( i = 30)
They said that, we have to beware cause it will lead to logical error rather thank syntax error.. ( it will be translated to if (30) )
But when we looked in higher langs like Java/C#, we found that, the compiler will issue a compilation error if he find such statement.
The difference appears because, in C/C++ there were originally bool datatype, so expressions were evaluated to zero and none-zero.
Zero for false, and non-zero for true.
So, the statement:
if (i = 30 )
Will always translated to if (30) which is a valid C/C++ statement that it understand as it were: if (true)
But in Java, relational expressions are only evaluated to Boolean types which is a completely separate type, which takes only two values, constant true and constant false.. so such statement will be always syntactically incorrect.
BTW, I could say that the following is the C implementation of true and false constants (implemented as macros):
#define FALSE 0
#define TRUE !FALSE
if ( i = 30)
They said that, we have to beware cause it will lead to logical error rather thank syntax error.. ( it will be translated to if (30) )
But when we looked in higher langs like Java/C#, we found that, the compiler will issue a compilation error if he find such statement.
The difference appears because, in C/C++ there were originally bool datatype, so expressions were evaluated to zero and none-zero.
Zero for false, and non-zero for true.
So, the statement:
if (i = 30 )
Will always translated to if (30) which is a valid C/C++ statement that it understand as it were: if (true)
But in Java, relational expressions are only evaluated to Boolean types which is a completely separate type, which takes only two values, constant true and constant false.. so such statement will be always syntactically incorrect.
BTW, I could say that the following is the C implementation of true and false constants (implemented as macros):
#define FALSE 0
#define TRUE !FALSE
Labels:
c,
C++,
General Programming Topics,
java,
thougts
02 June 2011
Playing with CGI
Hello,
I just want to play again with CGI, so today we will make a simple Hello Form.
And Here's the code:
First, the HTML Page:
And the CGI Script (simple C++ program):
I just want to play again with CGI, so today we will make a simple Hello Form.
And Here's the code:
First, the HTML Page:
<form action="/cgi-bin/sayHello" method="post" >
<input type="text" name="username" />
<input type="submit" value="say Hello" />
</form>
And the CGI Script (simple C++ program):
#include <iostream>
#include <cstdlib>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
int main(void)
{
char* value = new char;
cout<< "Content-type: text/html" << endl << endl;
cin >> value;
char* newValue = new char;
bool toCpy = false;
int cnt = 0;
while (*value != '\0')
{
if (toCpy)
{
*newValue = *value;
newValue++;
cnt++;
}
if (toCpy == false && *value == '=')
{
toCpy = true;
}
value++;
}
newValue = newValue - cnt;
cout<<"Hello " << newValue<<endl;
}
18 February 2011
Your First CGI script using C....
Hello buddies..
This is actually my first CGI script... at all..
So, let me transfer this piece of knowledge to you.
First we will install the server on our local machine. (I am assuming you are using Linux)
From you package manager, install mini-http (you can use apache server instead .. but step here is for mini-http)
In my case, I am using ubuntu, so from synabtic I searched for "mini-http" them mark it for installation.. and then I got installed in moments.
after installing mini-http.. cd your hame folder:
Now lets start the web server..
start your browse at:
http://localhost/
it should show listing of files of the directory at which you started the server at (in our case, the home directory)
Now let's write our simple application... I'll used httputil which I created in a previous post
Now compile this source file ...
First, get the required .h and .c files from the link above:
so you'll have 5 files, 3 .c and 2.h
stringutil.h, stringutil.c, httputil.h, httputil.c and the one above, let's name "employee.c"
then copy the generated "employee" file and past it in ~/cgi-bin/employee.cgi
Now restart the server:
Now fire your browse at:
http://localhost/cgi-bin/employee.cgi?empId=20
You should see:
That's all...
Next post I'll try to making GWT make a cross-site call to another server running CGI
...
This is actually my first CGI script... at all..
So, let me transfer this piece of knowledge to you.
First we will install the server on our local machine. (I am assuming you are using Linux)
From you package manager, install mini-http (you can use apache server instead .. but step here is for mini-http)
In my case, I am using ubuntu, so from synabtic I searched for "mini-http" them mark it for installation.. and then I got installed in moments.
after installing mini-http.. cd your hame folder:
cd $HOME
#then:
mkdir cgi-bin
Now lets start the web server..
cd ~
sudo mini-httpd -c "cgi-bin/*" # now the mini-httpd should starts ..
#to stop it write:
#sudo fuser -k 80/tcp
start your browse at:
http://localhost/
it should show listing of files of the directory at which you started the server at (in our case, the home directory)
Now let's write our simple application... I'll used httputil which I created in a previous post
#include <stdio.h>
#include <stdlib.h>
#include "httputil.h"
static void writeHeaders();
int main(void)
{
writeHeaders();
char* empId = get_parameter("empId");
printf("you enterd employee Id: %s\n", empId);
free(empId);
return 0;
}
static void writeHeaders()
{
printf("content-type: text/plain;charset=UTF-8\n\n");
}
Now compile this source file ...
First, get the required .h and .c files from the link above:
so you'll have 5 files, 3 .c and 2.h
stringutil.h, stringutil.c, httputil.h, httputil.c and the one above, let's name "employee.c"
cc -c stringutil.c
cc -c httputil.c
cc -o employee employee.c -L. *.o
then copy the generated "employee" file and past it in ~/cgi-bin/employee.cgi
Now restart the server:
sudo fuser -k 80/tcp
sudo mini-httpd -c "cgi-bin/*"
Now fire your browse at:
http://localhost/cgi-bin/employee.cgi?empId=20
You should see:
That's all...
Next post I'll try to making GWT make a cross-site call to another server running CGI
...
httputil: my c library for http utilities
Hello every body,
Salamo Alaykom Wa rahmat Allah,
In a previous post, I wrote about my string util.. now I'll take about my http util..
It contains just one function, `get_parameter`, get parameter value from `getenv("QUERY_STRING")` env variable (to be used within CGI)..
here's the lib:
This library uses the stringutil library
You can convert this library into a static lib on linux.. follow this post
Salamo Alaykom Wa rahmat Allah,
In a previous post, I wrote about my string util.. now I'll take about my http util..
It contains just one function, `get_parameter`, get parameter value from `getenv("QUERY_STRING")` env variable (to be used within CGI)..
here's the lib:
#ifndef _HTTP_UTIL_
#define _HTTP_UTIL_
static char ***out;
/**
* get parameter value from the QUERY_STRING
* return NULL if QUERY_STRING is null or the key has no associated value or if key found but without a value
* returns pointer to char that you should free after use.
*/
char* get_parameter(char*);
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "stringutil.h"
static char ***out;
/**
* get parameter value from the QUERY_STRING
* return NULL if QUERY_STRING is null or the key has no associated value or if key found but without a value
*/
char* get_parameter(char* key)
{
char *querystr = getenv("QUERY_STRING");
if (querystr == NULL)
return (void*)0;
char s[strlen(querystr)] ;
strcpy(s, querystr);
const char delim = '&';
const char delim2 = '=';
static size_t size = 0;
if (out == 0)
{
out = malloc(sizeof(char));
size = split(s, &delim, out);
}
int i=0;
for (; i<size; i++)
{
char* seg = (*out)[i];
if (seg != NULL)
{
char ***iout = malloc(sizeof(char));
int isize = split(seg, &delim2, iout);
if (isize > 1 && ((*iout)[1]) != NULL && strcmp(key, (*iout)[0]) == 0)
{
size_t _size = strlen((*iout)[1]);
char* value = (char*) malloc(_size*sizeof(char));
strcpy(value, (*iout)[1]);
free(iout);
return value;
}
}
}
return (void*) 0;
}
This library uses the stringutil library
You can convert this library into a static lib on linux.. follow this post
stringutil: my c library for string utilities
Hello,
I am working on some task in CGI, I'll try to write some string utility functions to help me simplify task..
this lib is still simple, It just contains 1 non-static function `split`
I am working on some task in CGI, I'll try to write some string utility functions to help me simplify task..
this lib is still simple, It just contains 1 non-static function `split`
#ifndef _STRING_UTIL_
#define _STRING_UTIL_
static size_t count(const char*, char);
size_t split(const char *const, const char*, char***);
#endif
#include <string.h>
#include <stdlib.h>
#include "stringutil.h"
static size_t count(const char *str, char ch)
{
if (str == NULL) return 0;
size_t count = 1;
while (*str)
if (*str++ == ch) count++;
return count;
}
size_t split(const char *const str, const char* delim, char ***out)
{
size_t size = count(str, *delim);
*out = calloc(size, sizeof(char));
char* token = NULL;
char* tmp = (char*) str;
int i=0;
while ((token = strtok(tmp, delim)) != NULL)
{
tmp = NULL;
(*out)[i] = (char*) malloc(sizeof strlen(token) * 4 /* to solve some bug */);
strcpy((*out)[i++], token);
}
return size;
}
12 February 2011
How to write a static library in Linux
I am going to illustrate how to write a static library in C for Linux.
requirements: a Linux distribution with GCC installed.
1- First, we need to write the header file of our library:
this command will output a files named "complex.o", and it is the object file for our library
4- static libraries in C are archives that contains object files, so let's archive our object file.
use the following command :
libcomplex.a: is the name of our library, it should start with "lib" and ends by ".a" and in between, you can name it as you like.
complex.o: is our object file generated from compiling complex.c in step 3
notice the generation of the library file libcomplex.a
5- we are done!, so let's examine the generated files before using the library.
First, we can use the command "nm" to see the symbols in our object file, use this command:
let's examine the library too:
-L. : this instruct the linker (ld) to include the current directory among the paths it searches for locating object files/libraries. (so it can look in our libcomplex.a library)
this command will generate the binary file for us, it will be named "program", try executing it:
also, we can list symbols in this binary using th "nm" tool too.
thats all.
References:
Beginning Linux Programming, third edition, Wiley Publishing, Inc.
requirements: a Linux distribution with GCC installed.
1- First, we need to write the header file of our library:
// complex.h
#ifndef _COMPLEX_H
#define _COMPLEX_H
typedef struct
{
double real;
double imaginary;
}complex_t;
void add(complex_t *const dest, const complex_t *const src);
static int assert_ptr_not_null(void *);
#endif
2- second, let's write the implementation for this libary://complex.c
#include <stdio.h>
#include "complex.h"
void add(complex_t *const dest, const complex_t *const src)
{
if ( !assert_ptr_not_null((void*)dest) || !assert_ptr_not_null((void*)src) )
{
fprintf(stderr, "NULL Pointers passed");
return;
}
dest->real = dest->real + src->real;
dest->imaginary = dest->imaginary + src->imaginary;
}
static int assert_ptr_not_null(void *ptr)
{
if (ptr == NULL) return 0;
return 1;
}
3- let's compile the library (but not link it), use the following command to compile the library:>cc -c complex.c
-c tell the compiler not to do the linking phasethis command will output a files named "complex.o", and it is the object file for our library
4- static libraries in C are archives that contains object files, so let's archive our object file.
use the following command :
>ar libcomplex.a complex.o
ar: is a regular archiving program found in Linux.libcomplex.a: is the name of our library, it should start with "lib" and ends by ".a" and in between, you can name it as you like.
complex.o: is our object file generated from compiling complex.c in step 3
notice the generation of the library file libcomplex.a
5- we are done!, so let's examine the generated files before using the library.
First, we can use the command "nm" to see the symbols in our object file, use this command:
>nm complex.o
the output will be like:
00000000 T add
00000075 t assert_ptr_not_null
U fwrite
U stderr
Notice the existence of our functions (assert_ptr_not_null, add)let's examine the library too:
>nm libcomplex.a
complex.o:
00000000 T add
00000075 t assert_ptr_not_null
U fwrite
U stderr
6- now, lets use the libary, here's a test program that uses the library://program.c
#include <stdio.h>
#include <stdlib.h>
#include "complex.h"
int
main()
{
complex_t *c1 = (complex_t*) malloc(sizeof (complex_t));
complex_t *c2 = (complex_t*) malloc(sizeof (complex_t));
c1->real = 10;
c1->imaginary = 10;
add(c1, c2);
printf("%f\n", c1->real);
printf("%f\n", c1->imaginary);
printf("%f\n", c2->real);
printf("%f\n", c2->imaginary);
free(c1);
free(c2);
return 0;
}
first, we need to compile our program:>cc -c program.c
then, it's time for linking the generated object file:> cc -o program program.o -L. -lcomplex
-lcomplex: composed of "-l" + "complex" which is our library name (without both "lib" and ".a").-L. : this instruct the linker (ld) to include the current directory among the paths it searches for locating object files/libraries. (so it can look in our libcomplex.a library)
this command will generate the binary file for us, it will be named "program", try executing it:
>./program
also, we can list symbols in this binary using th "nm" tool too.
thats all.
References:
Beginning Linux Programming, third edition, Wiley Publishing, Inc.
02 December 2010
Stack infix in C
Based on the post of "Stack implementation in C", here's Stack infix implementation in C:
// the idea of this example from "Data Structures and Algorithms using C#"
// main_stack_infix.c
#include <stdio.h>
#include <ctype.h>
#include "stack.h"
#define CHAR_TO_INT(x) ((x)-48)
void calc(struct stack*, struct stack*);
int main(void)
{
struct stack s1, s2;
char *equation = "1 + 2 - 9 ";
int count=0;
init(&s1);
init(&s2);
while (*equation != '\0')
{
if (count == 2)
{
calc(&s1, &s2);
count=1;
}
if (isdigit(*equation) != 0)
{
push(&s1, CHAR_TO_INT(*equation));
count++;
}else if (ispunct(*equation) != 0)
{
push(&s2, *equation);
}
equation++;
}
printf("%i\n", peek(&s1));
return 0;
}
void calc(struct stack *s1, struct stack *s2)
{
int x = pop(s1);
int y = pop(s1);
int op = pop(s2);
int ret = 0;
switch (op)
{
case '+':
ret = y+x;
break;
case '-':
ret = y-x;
break;
case '*':
ret = y*x;
break;
case '/':
ret = y/x;
break;
}
push(s1, ret);
}
Stack implementation in C
Hi folks,
I've written a stack implementation in C from sometime ago, and I'd like to share with you.
I've written a stack implementation in C from sometime ago, and I'd like to share with you.
#ifndef STACK_H
#define STACK_H
#define STACK_SIZE 100
struct stack
{
int data[STACK_SIZE];
int top;
};
void init(struct stack*);
void push(struct stack*, int);
int pop(struct stack*);
int peek(struct stack*);
int is_empty(struct stack*);
int is_full(struct stack*);
void print(struct stack*);
int count(struct stack*);
#endif
#include <stdio.h>
#include <errno.h>
#include "stack.h"
void init(struct stack *s)
{
s->top = -1;
}
void push(struct stack *s, int value)
{
if (!is_full(s))
s->data[++(s->top)] = value;
else
fprintf(stderr, "StackOverFlow\n");
}
int pop(struct stack *s)
{
int ret = peek(s);
if (errno == 0)
s->top--;
errno=0; // non-throw the exception
return ret;
}
int peek(struct stack *s)
{
if (!is_empty(s))
return s->data[s->top];
else
{
fprintf(stderr, "StackUnderFlow\n");
errno = 200; // throw an exception to the calling method (in C way)
return -1;
}
}
int is_empty(struct stack *s)
{
return (s->top == -1);
}
int is_full(struct stack *s)
{
return (s->top == STACK_SIZE-1);
}
void print(struct stack *s)
{
int i;
for (i=0; i<= s->top ; i++)
{
printf("%i\n", s->data[i]);
}
}
int count(struct stack *s)
{
return s->top + 1;
}
20 September 2010
Java-like ArrayList in C
Al salamo Alykom,
Last week I had the change to have a look at the implementation of the java.util.ArrayList class in Java.
I decided to write a similar one in C, and hence it is fully depended on System.arraycopy, so I wrote arrayCopyutility function in C to use it.
The implementation of ArrayList we going to see here is depending on code wrote under the post of ArrayCopy.
I tried to include many of the functions of the java.util.ArrayList, and also missed many :).
Here's the header file:
And here's the implementation file:
And here's a test program:
That's all folks.
Just make sure to test the above code well before using it.
Last week I had the change to have a look at the implementation of the java.util.ArrayList class in Java.
I decided to write a similar one in C, and hence it is fully depended on System.arraycopy, so I wrote arrayCopyutility function in C to use it.
The implementation of ArrayList we going to see here is depending on code wrote under the post of ArrayCopy.
I tried to include many of the functions of the java.util.ArrayList, and also missed many :).
Here's the header file:
/*
* ArrayList
*/
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
typedef struct
{
int data;
}Element;
typedef struct
{
int current;
int size;
int increment_rate;
Element *elements;
}ArrayList;
typedef enum
{
RIFHT, LEFT
} Shift;
// public functions:
void init (ArrayList*const);
void initWithSize (ArrayList*const, int);
void initWithSizeAndIncRate (ArrayList*const, int, int);
void clean (ArrayList*);
int add (ArrayList*const, Element);
int insert (ArrayList*const, Element, int);
Element* removeAt (ArrayList*const, int);
void clear (ArrayList*const);
int set (ArrayList*const, Element, int);
Element* get (ArrayList*const, int);
void print (const ArrayList*const);
int lastIndexOf (const ArrayList*const, Element);
int indexOf (const ArrayList*const, Element);
int isEmpty (const ArrayList*const);
// TODO
int hashCode (const ArrayList*const);
// static (private) utility functions:
/* Abstracting the print method of the element by delegating it to the element itself (OOP-like feature) */
static void printElement(const Element*const);
static void shift(ArrayList *const list, int index, int rooms, Shift dir);
static void wide(ArrayList* const);
#endif // ARRAYLIST_H
And here's the implementation file:
#include <stdio.h>
#include <stdlib.h>
#include <array_list_impl/ArrayList.h>
#include <arrays/ArrayUtil.h>
void init (ArrayList *const list)
{
initWithSize(list, 100);
}
void initWithSize(ArrayList *const list, int size)
{
initWithSizeAndIncRate(list, size, 50);
}
void initWithSizeAndIncRate(ArrayList *const list, int size, int rate)
{
list->size = size;
list->increment_rate = rate;
list->elements = (Element*) calloc(sizeof(Element), list->size);
list->current = -1;
}
void clear (ArrayList *const list)
{
while (list->current>=0)
{
list->elements[list->current] = (Element){0};
list->current--;
}
}
int set (ArrayList *const list, Element e, int index)
{
if (index <= list->current)
{
list->elements[index] = e;
}
return 0;
}
Element* get (ArrayList *const list, int index)
{
if (index <= list->current)
{
Element *e = &list->elements[index];
return e;
}
return NULL;
}
int add (ArrayList *const list, Element e)
{
if (++list->current < list->size)
{
list->elements[list->current] = e;
return 1;
}else
{
wide(list);
list->elements[list->current] = e;
return 1;
}
return 0;
}
static void wide(ArrayList* const list)
{
list->size += list->increment_rate;
Element *newArr = (Element*) calloc(sizeof(Element), list->size) ;
arraryCopy(newArr, 0, list->elements, 0, list->current, list->size, sizeof(Element));
free(list->elements);
list->elements = newArr;
}
int insert (ArrayList *const list, Element e, int index)
{
if (index <= list->current && ++list->current < list->size)
{
shift(list, index, 1, RIFHT);
list->elements[index] = e;
return 1;
}
return 0;
}
int lastIndexOf (const ArrayList *const list, Element e)
{
int index = list->current;
while (index >-1)
{
if (e.data == list->elements[index].data) return (list->current-index);
index--;
}
return 0;
}
int indexOf (const ArrayList *const list, Element e)
{
int index = 0;
while (index <= list->current)
{
if (e.data == list->elements[index].data) return index;
index++;
}
return 0;
}
int isEmpty (const ArrayList *const list)
{
return list->current == -1;
}
Element *removeAt(ArrayList *const list, int index)
{
if (list->current >= index)
{
Element *e = &list->elements[index];
shift(list, index, 1, LEFT);
list->current--;
return e;
}
return NULL;
}
void print (const ArrayList *const list)
{
int i;
for (i=0; i<=list->current; i++)
{
Element e = list->elements[i];
printElement(&e);
}
printf("\n");
}
void clean(ArrayList *list)
{
free(list->elements);
}
static void printElement(const Element *const e)
{
printf("%i ", e->data);
}
static void shift(ArrayList *const list, int index, int rooms, Shift dir)
{
if (dir == RIFHT)
{
arraryCopy(list->elements, index+1, list->elements, index, rooms, list->current, sizeof(Element));
}else //SHIFT
{
arraryCopy(list->elements, index, list->elements, index+1, rooms, list->current, sizeof(Element));
}
}
And here's a test program:
#include <stdio.h>
#include <array_list_impl/ArrayList.h>
int main(void)
{
ArrayList list;
init(&list);
add(&list, (Element){10});
add(&list, (Element){30});
add(&list, (Element){40});
add(&list, (Element){50});
add(&list, (Element){60});
add(&list, (Element){30});
add(&list, (Element){80});
print(&list);
insert(&list, (Element){20}, 1);
insert(&list, (Element){15}, 1);
insert(&list, (Element){3}, 0);
print(&list);
printf("Removeing element at index 5\n");
removeAt(&list, 5);
print(&list);
Element *e = get(&list, 5);
printf("element at 5th index:\n %i\n", (e!=NULL? e->data:-1));
int i = indexOf(&list, (Element){30});
printf("Index of 30:\n %i\n", i);
i = lastIndexOf(&list, (Element){30});
printf("Last index of 30:\n %i\n", i);
printf("Clear...\n");
clear(&list);
print(&list);
for (i=0; i<180; i++)
{
add(&list, (Element){i});
}
print(&list);
clean(&list);
return 0;
}
That's all folks.
Just make sure to test the above code well before using it.
arrayCopy
Hi folks,
While looking at the usage of the method System.arraycopy
in Java, I found it very useful function.
for example, in java.util.ArrayList it is doing may useful shifting operations.
So, I decide to try to write a similar function, but instead of using the pattern "func (src, dest)" of java, I used instead the pattern "func(dest, src)" of C.
The Header file:
The impl file:
And, testing it:
While looking at the usage of the method System.arraycopy
in Java, I found it very useful function.
for example, in java.util.ArrayList it is doing may useful shifting operations.
So, I decide to try to write a similar function, but instead of using the pattern "func (src, dest)" of java, I used instead the pattern "func(dest, src)" of C.
The Header file:
#ifndef ARRAYUTIL_H
#define ARRAYUTIL_H
#include <stddef.h>
/**
* dest destination array
* dIndex index to which we will start copying
* src source array
* sIndex index from which we will start copying
* len number of elements that will be copied from source array
* destArrLen the length of the destination array (hence C doesn't know any length info about passed arrays)
* size the size of the type of the array (ex: if the array of type long, put in this parameter sizeof(long))
*/
void arraryCopy(void *dest, int dIndex, const void* src, int sIndex, int len, int destArrLen, size_t size);
#endif // ARRAYUTIL_H
The impl file:
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <arrays/ArrayUtil.h>
void arraryCopy(void *dest, int dIndex, const void* src, int sIndex, int len, int destLen, size_t size)
{
uint8_t *udest = (uint8_t*) dest;
uint8_t *usrc = (uint8_t*) src;
dIndex *= size;
sIndex *= size;
len *= size;
destLen *= size;
if (src != dest)
{
memcpy(&udest[dIndex], &usrc[sIndex], len);
}else
{
if (dIndex > sIndex)
{
uint8_t *tmp = (uint8_t*) calloc(destLen, size);
memcpy(tmp, &udest[dIndex], (destLen-dIndex));
memcpy(&udest[dIndex], &usrc[sIndex], len);
memcpy(&udest[dIndex+len], tmp, (destLen-dIndex));
free(tmp);
}else if (sIndex > dIndex)
{
memcpy(&udest[dIndex], &usrc[sIndex], (destLen-sIndex)+1);
}else
return;
}
}
And, testing it:
#include <stdio.h>
#include <arrays/ArrayUtil.h>
int main(void)
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
arraryCopy(arr, 1, arr, 2, 1, 10, sizeof(int));
int i;
for (i=0; i<9; i++) // the len became 9 here because we do shift left by 1
printf("%i ", arr[i]);
return 0;
}
17 September 2010
Lined Lists vs Array Lists, a quick view
Alsalamo Alykom,
Lists in many programming languages are implemented in many ways such as linked lists, Array Lists.http://www.blogger.com/img/blank.gif
Linked lists are about nodes being linked together, and It may be single or doubly linked lists.
the insertion and deletion operations are simply done by changing the destination of some pointers. But the search is liner!.
In Array list, the Array Lists is used technique called dynamic-arrays, in which these lists is built based on arrays.
Also, you can still insert and remove elements from ArrayLists such as you done with Lined Lists, but this operation uses shifting operation as an underlying operation.
For example, in Java, java.uitl.ArrayList class uses System.arraycopy to do the shift of elements.
ArrayLists is very efficient in Random access.
thanks all folks!
Lists in many programming languages are implemented in many ways such as linked lists, Array Lists.http://www.blogger.com/img/blank.gif
Linked lists are about nodes being linked together, and It may be single or doubly linked lists.
the insertion and deletion operations are simply done by changing the destination of some pointers. But the search is liner!.
In Array list, the Array Lists is used technique called dynamic-arrays, in which these lists is built based on arrays.
Also, you can still insert and remove elements from ArrayLists such as you done with Lined Lists, but this operation uses shifting operation as an underlying operation.
For example, in Java, java.uitl.ArrayList class uses System.arraycopy to do the shift of elements.
ArrayLists is very efficient in Random access.
thanks all folks!
15 September 2010
ASCII to hex
Alsalamo Alaykom whoever following me :)
Today I am coming for you with a complete app in C, it is simple but yet complete and do a great job.
For some reason I wanted to convert from ASCII to hex, I know that many Linux app already exist for that (oc, hexdump), but may be I found them hard to use correctly :)
The following is a simple but complete app you can use for that purpose, have fun :) :
Example of usage:
atohex.exe -s ABC
atohex.exe -s 1
atohex.exe hello
Today I am coming for you with a complete app in C, it is simple but yet complete and do a great job.
For some reason I wanted to convert from ASCII to hex, I know that many Linux app already exist for that (oc, hexdump), but may be I found them hard to use correctly :)
The following is a simple but complete app you can use for that purpose, have fun :) :
/*
* @auther mhewedy
* @email mohammed_a_hewedy@hotmail.com
* @tested under gcc (GCC) 3.4.2 (mingw-special) (quite old :) )
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* usage(char*);
int main(int argc, char* argv[])
{
if (argc <= 1)
{
char* usage_string = usage(argv[0]);
printf("%s\n", usage_string);
free(usage_string);
exit(1);
}
int s_option_present =0;
char* string = NULL;
if (strcmp("-s", argv[1]) != 0)
string = argv[1];
else
{
string = argv[2];
s_option_present = 1;
}
while (*string != '\0')
{
printf("%X%s", *string++, (s_option_present? " " : ""));
}
printf("\n");
return 0;
}
char* usage(char* app_name)
{
char* usage = (char*) calloc(40, sizeof(char*));
strcpy(usage, "Usage: ");
strcat(usage, app_name);
strcat(usage, " [-s] {ascii string}");
return usage;
}
Example of usage:
atohex.exe -s ABC
atohex.exe -s 1
atohex.exe hello
Subscribe to:
Posts (Atom)