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 basics. Show all posts
Showing posts with label basics. Show all posts
15 January 2012
26 August 2011
Class methods in Java vs Objective-C
The are not the same!
Yes, although their usage is the same (singleton methods, factory methods, utility methods)
But actually class methods in ObjC is looks like instance methods. but in java they are t treated differentially than instance methods ..
Watch this example in Java (in seconds we will write it in ObjC and compare the results):
Will print : in A
Now lets see how Objective C treat the same situation:
Will Print: in B
Conclusion:
class methods in Objective-C differ from Java.
In Java, class methods don't override each other but hide each other. Also, class methods which comes in no context (when don't being called in any other object), it calls the methods in the same class regardless whom object is calling it.
In Objective C, the existence of self keyword in the class methods make it possible to call functions based on the caller itself (self returns to the object/class that calls the function).
Yes, although their usage is the same (singleton methods, factory methods, utility methods)
But actually class methods in ObjC is looks like instance methods. but in java they are t treated differentially than instance methods ..
Watch this example in Java (in seconds we will write it in ObjC and compare the results):
1. 2. public class Abc 3. { 4. public static void main(String[] args) 5. { 6. B.func(); 7. // 1- B will inherit `func() from A. 8. // 2- `func()` call the method `x()` 9. // 3- since `func()` is a static method in Class A, it will reference non-qualified methods as static methods in the same class 10. // 4- `func()` will call `x()` from the same class it resids in (class A) 11. } 12. } 13. 14. class A 15. { 16. static void x() 17. { 18. System.out.println("in A"); 19. 20. } 21. 22. static void func() 23. { 24. x(); // as if we call : A.x(); 25. } 26. } 27. 28. class B extends A 29. { 30. static void x() 31. { 32. System.out.println("in B"); 33. 34. } 35. }
Will print : in A
Now lets see how Objective C treat the same situation:
1. //A.h 2. #import <Foundation/Foundation.h> 3. 4. @interface A : NSObject 5. 6. +(void) x; 7. +(void) func; 8. 9. @end 10. 11. @implementation A 12. +(void) x 13. { 14. NSLog(@"in A"); 15. } 16. +(void) func 17. { 18. [self x]; 19. } 20. 21. @end
1. //B.h 2. #import <Foundation/Foundation.h> 3. #import "A.h" 4. 5. @interface B : A 6. 7. +(void) x; 8. 9. @end 10. 11. @implementation B 12. 13. +(void) x 14. { 15. NSLog(@"in B"); 16. } 17. 18. @end
1. //Main.m 2. #import <Foundation/Foundation.h> 3. #import "B.h" 4. 5. int main(void) 6. { 7. 8. [B func]; 9. 10. return 0; 11. }
Will Print: in B
Conclusion:
class methods in Objective-C differ from Java.
In Java, class methods don't override each other but hide each other. Also, class methods which comes in no context (when don't being called in any other object), it calls the methods in the same class regardless whom object is calling it.
In Objective C, the existence of self keyword in the class methods make it possible to call functions based on the caller itself (self returns to the object/class that calls the function).
22 August 2011
Control the appearance of null objects when sorting a collections
SA,
In Java, if you have a list of object and need to order this list.. you have to implement either java.lang.Comparable or java.util.Comporator..
Here's a simple Java class that we need to order it:
The point here is in the `compareTo` method in the line:
if (o == null) return -1;
This means if the parameter is null, move it to the bottom of the list..
In Java, if you have a list of object and need to order this list.. you have to implement either java.lang.Comparable or java.util.Comporator..
Here's a simple Java class that we need to order it:
1. public class Param implements Comparable<Param> 2. { 3. int paramNo; 4. String value; 5. 6. public int compareTo(Param o) 7. { 8. if (o == null) 9. return -1; 10. return new Integer(this.paramNo).compareTo(o.paramNo); // thanks to autoboxing 11. } 12. 13. public String toString() 14. { 15. return "Param [paramNo=" + paramNo + ", value=" + value + "]"; 16. } 17. }
The point here is in the `compareTo` method in the line:
if (o == null) return -1;
This means if the parameter is null, move it to the bottom of the list..
22 November 2010
Never uses "OutputStream.write(byte[])"
Alslamoa Alykom folks,
Today I am gonna talking about very important IO note, I saw some people usually fail to notice!
Well, the problem here is, when you use a buffer to fill in some OutputStream, you usually write the latest buffer as is with some invalid data (from last value of the buffer).
See the following example:
Notice, if you uses baos.write(buffer) instead of the one that takes off-site and size you will have the OutputStream contains corrupted data!
Today I am gonna talking about very important IO note, I saw some people usually fail to notice!
Well, the problem here is, when you use a buffer to fill in some OutputStream, you usually write the latest buffer as is with some invalid data (from last value of the buffer).
See the following example:
FileInputStream fis = new FileInputStream("D:/tmp/some_long_file.txt"); // some long file
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // if you have a small file, try to reduce the value here to notice the output
int i;
while ((i = fis.read(buffer)) != -1)
baos.write(buffer, 0, i); //never use: baos.write(buffer);
fis.close();
baos.close();
// notice the ouput of this line:
System.out.println(baos.toString());
Notice, if you uses baos.write(buffer) instead of the one that takes off-site and size you will have the OutputStream contains corrupted data!
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!
31 August 2010
Portability tip: How to know the size of primitive data types on your machine
In C the size of primitive data types are machine and compiler dependent.
So, you shouldn't make any assumption when about the max number that int or short or any other primitive data types can hold.
But, by applying the following trick, you can get the max number of bits each primitive type can hold.
So, you shouldn't make any assumption when about the max number that int or short or any other primitive data types can hold.
But, by applying the following trick, you can get the max number of bits each primitive type can hold.
/**
* @auther: mhewedy
* @date 31/08/2010
* get_types_bits.c
*/
#include <stdio.h>
int int_bits();
int short_bits();
int long_bits();
int long_long_bits();
int char_bits();
int main(void)
{
printf("%i %i %i %i %i\n",char_bits(), short_bits(), int_bits(), long_bits(), long_long_bits());
return 0;
}
int int_bits()
{
unsigned int x = ~0;
int c=0;
while (x>0)
{
x>>=1;
c++;
}
return c;
}
int short_bits()
{
unsigned short int x = ~0;
int c=0;
while (x>0)
{
x>>=1;
c++;
}
return c;
}
int long_bits()
{
unsigned long int x = ~0;
int c=0;
while (x>0)
{
x>>=1;
c++;
}
return c;
}
int long_long_bits()
{
unsigned long long int x = ~0;
int c=0;
while (x>0)
{
x>>=1;
c++;
}
return c;
}
int char_bits()
{
unsigned char x = ~0;
int c=0;
while (x>0)
{
x>>=1;
c++;
}
return c;
}
13 August 2010
simple dictionary using binary search
//strcmp.c
#include <stdio.h>
int my_strcmp(const char[], const char[]);
/*
// testing..
int main(void)
{
printf("%i\n", strcmp("alpha", "altered"));
printf("%i\n", strcmp("zioty", "yucca"));
getchar();
return 0;
}
*/
int my_strcmp(const char str1[], const char str2[])
{
int i=0;
while (str1[i] == str2[i] && str1[i] != '\0' && str2[i] != '\0')
i++;
if (str1[i] > str2[i])
return 1;
else if (str1[i] < str2[i])
return -1;
else
return 0;
}
// simple dictionary using binary search
// auther mhewedy
// date : 2010-08-13
// compiled under GCC 4.x
#include <stdio.h>
#include <string.h>
#include "strcmp.c"
#define DICT_LENGTH 3
typedef struct _dictionary_s dictionary;
struct _dictionary_s
{
char word[20];
char definition[50];
};
int lookup(const char[], const dictionary[], int);
int binary_lookup(const char[], const dictionary[], int, int);
int main(void)
{
static const dictionary dict[DICT_LENGTH] =
{
{"a", "first letter in alphabatic"},
{"b", "second letter"},
{"c", "third letter"}
};
char word[20];
int ret=-1;
do{
printf("Enter word: \n");
if (gets(word) == NULL)
break;
ret = binary_lookup(word, dict, 0, DICT_LENGTH-1);
if (ret < 0)
{
fprintf(stderr, "word not found!\n");
}
else{
printf("%s : %s\n", word, dict[ret].definition);
}
printf("\n");
}while (1);
return 0;
}
int binary_lookup(const char word[], const dictionary dict[], int start, int end)
{
if (start > end)
return -1;
int middle = (start+end)/2;
int cmp = my_strcmp(word, dict[middle].word);
if (cmp == -1)
{
end = middle -1;
binary_lookup(word, dict, start, end);
}
else if (cmp == 1)
{
start = middle +1;
binary_lookup(word, dict, start, end);
}
else // 0
{
return middle;
}
}
int lookup(const char word[], const dictionary dict[], int length)
{
int i;
for (i=0; i<length; i++)
{
if (strcmp(word, dict[i].word) == 0)
return i;
}
return -1;
}
12 August 2010
Constant Strings in C
#include <stdio.h>
int main(void)
{
printf("Programming " "in C \
lang " "is fun!" "\n");
return 0;
};
MHO about famous C/C++ Editors/IDEs
Al Salamo Alykom,

Hi folks,
I just want to talk about my very small period experience with C IDEs.
For Java, Eclipse is #1 at all. but for C, it differs.
First, I'll talk of C junior programmer that aims to find a simple/powerful IDE/Editor to help him just to try out simple programs.
for Eclipse, I don't like its experience with C + it is heavyweight.
for VC++, It is WIN only product, and It is not simple to use GCC with it. (and It is from M$)
for DEV-C++, It is powerful ,but it is also a WIN only product (and outdated too)
for NetBeans, Like Eclipse, It is heavyweight + I don't like it :).
for VI/Gedit/Kate/Notepad++, it is great, but we just want to do things fast(Yea I know we can use plug-ins, and If so, it will be very powerful candidate)
for QT Creator, It is more siutable for C++/QT development.
for Code::Blocks, It is simple, fast, multi-platform, can use with dozens of compilers, but I am trying now to obtain a auto-complete feature for C std library fun, and I think I can get it working...
EDIT:
I just tried Geany IDE, and found it the best candidate for beginners.
I tried QT Creator, and found it a professional tool worth using....
Hi folks,
I just want to talk about my very small period experience with C IDEs.
For Java, Eclipse is #1 at all. but for C, it differs.
First, I'll talk of C junior programmer that aims to find a simple/powerful IDE/Editor to help him just to try out simple programs.
for Eclipse, I don't like its experience with C + it is heavyweight.
for VC++, It is WIN only product, and It is not simple to use GCC with it. (and It is from M$)
for DEV-C++, It is powerful ,but it is also a WIN only product (and outdated too)
for NetBeans, Like Eclipse, It is heavyweight + I don't like it :).
for VI/Gedit/Kate/Notepad++, it is great, but we just want to do things fast(Yea I know we can use plug-ins, and If so, it will be very powerful candidate)
for QT Creator, It is more siutable for C++/QT development.
for Code::Blocks, It is simple, fast, multi-platform, can use with dozens of compilers, but I am trying now to obtain a auto-complete feature for C std library fun, and I think I can get it working...
EDIT:
I just tried Geany IDE, and found it the best candidate for beginners.
I tried QT Creator, and found it a professional tool worth using....
wc: very simple word count C program
It is a very trivial program that count the words in a file according to some policy.
// wc.c
// auther : mhewedy
#include <stdio.h>
#include <stdlib.h>
int wc(char*);
int main(int argc, char** argv)
{
FILE *fp = NULL;
char buff[100], *fileName = NULL;
int wcnt = 0;
if (argc <2)
{
fprintf(stderr, "Usage: wc <file_name>\n");
exit(1);
}
fileName = argv[1];
if ( (fp = fopen(fileName, "r")) == NULL)
{
perror(fileName);
exit(1);
}
while (!feof(fp))
{
buff[0] = '\0';
fgets(buff, sizeof buff/sizeof(char), fp);
wcnt += wc(buff);
}
fclose(fp);
printf("word count: %i words\n", wcnt);
return 0;
}
/*
Idea of this function taked from the book : Programming in C, thired edition
*/
int wc(char* line)
{
int is_alpha(int ch), wc=0;
int start_word = 1;
while (*line != '\0')
{
if (is_alpha(*line))
{
if (start_word)
{
start_word = 0;
wc++;
}
}else{
start_word = 1;
}
line++;
}
return wc;
}
int is_alpha(int ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
06 August 2010
Array Literals in C
#include <stdio.h>
void take_array(int[]);
int main(void)
{
take_array((int[]){1, 2, 3}); // here's the point, we must do cast here!
return 0;
}
void take_array(int arr[])
{
printf("IN: take_array(int[])\n");
}
strcat using arrays
#include <stdio.h>
void strcat2(char[], const char[], const char[]);
int main(void)
{
char a[] = "abc";
char b[] = "efg";
char ret[10];
strcat2(ret, a, b);
printf("%s\n", ret);
return 0;
}
void strcat2(char ret[], const char a[], const char b[])
{
int i=0, j=0;
while ( (ret[i++]=a[i]) != '\0');
i--;
while ( (ret[i++]=b[j++]) != '\0');
ret[i] = '\0';
}
30 July 2010
compound literal with struct of structs in C
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int hour, minute, second;
}Time;
typedef struct{
int day, month, year;
}Date;
typedef struct{
Time time;
Date date;
}DateTime;
int main(void)
{
DateTime dt = (DateTime){10, 9, 0,25, 11, 2010};
printf("%.2i:%.2i:%.2i\n", dt.time.hour, dt.time. minute, dt.time.second);
printf("%i/%i/%.2i\n", dt.date.day, dt.date.month, dt.date.year);
return 0;
}
22 July 2010
Print unicode values of non-ascii characters
class GetUnicode {
static final char digits[] = {'0', '1', '2', '3','4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static void main(String[] args) {
String name = "محمد هويدي";
for (char ch : name.toCharArray())
if (Character.isWhitespace(ch))
System.out.print(ch);
else
System.out.print("\\u" + getHex(ch));
}
static String getHex(int ch) {
char tmp[] = new char[32];
int i, j, count =0;
for (i=0; i<32; i++)
tmp[i] = '0';
while (ch>0)
{
int t = ch&0xf;
ch>>=4;
tmp[count++] = digits[t];
}
char ret[] = new char[count +=(4-count&3)]; // make ret size to be multiple of four
for (i=count-1, j=0; i>=0; i--, j++)
ret[j] = tmp[i];
tmp = null;
return new String(ret);
}
}
A Note about variable declaration and initialization in C vs Java
Al Salamo Alaykom,
I want to talk today about variable declarations in Java vs C.
First in Java:
We have two types of variables, method local variables and class member variables.
Class member variables (either instance or class variables):
are automatically initialized to default values which are for reference types is null and for primitive types (int, short, byte, float, double, char) is 0 (for boolean is false).
Note that, static member variables are initialized once the class get loaded by the class loader.
method local variables:
local variables in java doesn't have the concept of being static, it is always automatic variables.
It is not initialized automatically, however you cannot use it before you do the initialization yourself.
example, the following code spinet will generate compile-time error:
Second in C:
In C, we have two types of variables, Global variables and local variables.
Global variables:
Global variables are automatically initialized to default values, 0 for primitives, and NULL pointer for pointers.
local variables:
C has the concept of static local variables that automatically initialized to default values once the program get executed. it uses the same defaults as global variables.
for automatic local variables, it doesn't initialized automatically, but as opposite to java, it can be used without initialization, although it will hold garbage data! although, some compilers may generate warning messages.
I want to talk today about variable declarations in Java vs C.
First in Java:
We have two types of variables, method local variables and class member variables.
Class member variables (either instance or class variables):
are automatically initialized to default values which are for reference types is null and for primitive types (int, short, byte, float, double, char) is 0 (for boolean is false).
Note that, static member variables are initialized once the class get loaded by the class loader.
method local variables:
local variables in java doesn't have the concept of being static, it is always automatic variables.
It is not initialized automatically, however you cannot use it before you do the initialization yourself.
example, the following code spinet will generate compile-time error:
public static char getCh() {
char ch;
return ch; // compile error: The local variable ch may not have been initialized
}
Second in C:
In C, we have two types of variables, Global variables and local variables.
Global variables:
Global variables are automatically initialized to default values, 0 for primitives, and NULL pointer for pointers.
local variables:
C has the concept of static local variables that automatically initialized to default values once the program get executed. it uses the same defaults as global variables.
for automatic local variables, it doesn't initialized automatically, but as opposite to java, it can be used without initialization, although it will hold garbage data! although, some compilers may generate warning messages.
21 July 2010
BigInteger using C
The following is a very simple implementation for the addition and subtraction of a Big Integer using C. Actually It was my solution for some problem in some compitions of ArabTeam2000 forums
note, I have compiled it under GCC (4.5)
How to compile the program:
1- copy the three above files to a new directory (say c_big_int)
2- compile the BigInteger.c
3- make sure that the compilation process generated the object file:
5- Now you can run the program using the following command:
**EDIT** The code has been reformatted, if it is no longer working please let me know in the comments
note, I have compiled it under GCC (4.5)
//BigInteger.h
#ifndef BIG_INTEGER_H
#define BIG_INTEGER_H
typedef struct {
char *data;
size_t length;
short sign; // 0 for positive (default value), otherwise for negative
} BigInteger;
// BigInteger interface functions
/**
* The char array are provided from right to left, for example if you want to reprensent the number 200, you
* should use array looks like:
* char arr[] = {0, 0, 2};
*/
BigInteger* construct(char[], size_t);
BigInteger* add(BigInteger*, BigInteger*);
BigInteger* subtract(BigInteger*, BigInteger*);
char* get(BigInteger*);
void print(BigInteger*);
// utility functions
static void intcpy(char*, char*, int);
static char** get_adjusted(BigInteger*, BigInteger*);
#endif
//BigInteger.c
#include <stdio.h>
#include <stdlib.h>
#include "BigInteger.h"
BigInteger* construct(char data[], size_t length) {
if (length > 40)
return NULL;
BigInteger* bi = malloc(sizeof(BigInteger*));
bi->length = length;
bi->data = malloc(bi->length*sizeof(char));
intcpy(bi->data, data, bi->length);
return bi;
}
BigInteger* add(BigInteger* x, BigInteger* y) {
char* add_data(char*, char*, int*);
int len = (x->length > y->length) ? x->length : y->length;
char** resized = get_adjusted(x, y);
char* tmp_x = resized[0];
char* tmp_y = resized[1];
char* ret = add_data(tmp_x, tmp_y, &len);
if (ret == NULL)
return NULL;
BigInteger *b = construct(ret, len);
return b;
}
BigInteger* subtract(BigInteger* x, BigInteger* y) {
char** resized = get_adjusted(x, y);
char *tmp_x = resized[0];
char *tmp_y = resized[1];
enum Sign {
EQUAL = 0, POSITIVE = 1, NEGATIVE = 2
};
short ret_sign = EQUAL;
int i;
for (i = x->length - 1; i >= 0; i--) {
if (tmp_x[i] == tmp_y[i])
continue;
else if (tmp_x[i] > tmp_y[i]) {
ret_sign = POSITIVE;
break;
} else {
ret_sign = NEGATIVE;
break;
}
}
// TODO: separate the following logic into its own utility function
BigInteger* bi;
if (ret_sign == EQUAL) {
char ret[1] = {0};
bi= construct(ret, 1);
}else if (ret_sign == POSITIVE){
char ret[x->length];
for (i=0; i<x->length;i++){
int tmp = tmp_x[i]-tmp_y[i];
if (tmp <0){
tmp_x[i+1]--;
tmp = (tmp_x[i]+10)-tmp_y[i];
}
ret[i] = tmp;
}
bi=construct(ret, x->length);
}else{
char ret[y->length];
for (i=0; i<y->length;i++){
int tmp = tmp_y[i]-tmp_x[i];
if (tmp <0){
tmp_y[i+1]--;
tmp = (tmp_y[i]+10)-tmp_x[i];
}
ret[i] = tmp;
}
bi=construct(ret, y->length);
bi->sign = 1;
}
return bi;
}
char* get(BigInteger* bi) {
return bi->data;
}
void print(BigInteger* bi) {
char* d = bi->data;
if (bi->sign) printf("%c", '-');
int i;
for (i = (bi->length)-1; i>=0; --i) {
printf("%i", d[i]);
}
printf("\n");
}
char* add_data(char* x, char* y, int *len) {
int i, reminder = 0;
char *ret = malloc(sizeof(char) * *len);
for (i = 0; i < *len; i++) {
int tmp = x[i] + y[i] + reminder;
ret[i] = tmp % 10;
reminder = (tmp - ret[i]) / 10;
}
if (reminder) {
if (i==40){
fprintf(stderr, "Arithmetic OverFlown");
return NULL;
}else{
ret[i] =reminder;
(*len)++;
}
}
return ret;
}
static void intcpy(char* dest, char* src, int l) {
while (l-- > 0)
*dest++ = *src++;
}
static char** get_adjusted(BigInteger* x, BigInteger *y) {
char **ret = malloc(sizeof(char**));
int len = (x->length > y->length) ? x->length : y->length;
char *tmp_x = get(x);
char *tmp_y = get(y);
int diff;
if ((diff = len - x->length) > 0) {
intcpy(tmp_x, get(x), len);
while (diff > 0) {
tmp_x[x->length++] = 0;
diff--;
}
} else if ((diff = len - y->length) > 0) {
intcpy(tmp_y, get(y), len);
while (diff > 0) {
tmp_y[y->length++] = 0;
diff--;
}
}
ret[0] = tmp_x;
ret[1] = tmp_y;
return ret;
}
//main.c
#include <stdio.h>
#include "BigInteger.h"
void test_add1() {
printf("Start Testing ADD n");
char d1[] = { 1, 2}; // from right to left, so its value is 21
char d2[] = { 5}; // and this is 5
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = add(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_add2() {
printf("Start Testing ADD n");
char d1[40];
char d2[40];
int i=0;
for (i=0; i<40;i++){
d1[i] = 3;
d2[i] = 5;
}
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = add(bi1, bi2);
print(ret);
printf("End Testing...n");
}
/**
* Will print "Arithmetic Overflow" and returns NULL
*/
void test_add3() {
printf("Start Testing ADD n");
char d1[40];
char d2[40];
int i=0;
for (i=0; i<40;i++){
d1[i] = 5;
d2[i] = 5;
}
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = add(bi1, bi2);
if (ret == NULL)
printf("NULLn");
//print(ret);
printf("End Testing...n");
}
void test_add4() {
printf("Start Testing ADD n");
char d1[] = { 9, 9};
char d2[] = { 9, 9};
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = add(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_add5() {
printf("Start Testing ADD n");
char d1[] = { 1, 2, 0, 0, 1, 2, 3, 4, 5, 9 ,3, 1, 3, 4, 4, 2, 1}; // from right to left, so its value is 21
char d2[] = { 1, 3, 3, 4, 5, 5, 3, 0, 0, 0, 0, 0, 2, 1, 1, 1, 9}; // and this is 5
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = add(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_subtract1() {
printf("Start Testing SUBTRACT n");
char d1[] = { 1, 2}; // this is 21
char d2[] = { 5, 2}; // and this is 25
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = subtract(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_subtract2() {
printf("Start Testing SUBTRACT n");
char d1[] = { 9, 9};
char d2[] = { 9, 9};
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = subtract(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_subtract3() {
printf("Start Testing SUBTRACT n");
char d1[40];
char d2[40];
int i=0;
for (i=0; i<40;i++){
d1[i] = 3;
d2[i] = 5;
}
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = subtract(bi1, bi2);
print(ret);
printf("End Testing...n");
}
void test_subtract4() {
printf("Start Testing SUBTRACT n");
char d1[] = { 1, 2, 0, 0, 1, 2, 3, 4, 5, 9 ,3, 1, 3, 4, 4, 2, 1}; // from right to left, so its value is 21
char d2[] = { 1, 3, 3, 4, 5, 5, 3, 0, 0, 0, 0, 0, 2, 1, 1, 1, 9}; // and this is 5
BigInteger* bi1 = construct(d1, sizeof(d1) / sizeof(char));
BigInteger* bi2 = construct(d2, sizeof(d2) / sizeof(char));
print(bi1);
print(bi2);
BigInteger *ret = subtract(bi1, bi2);
print(ret);
printf("End Testing...n");
}
int main(void) {
test_add1();
test_add2();
test_add3();
test_add4();
test_add5();
test_subtract1();
test_subtract2();
test_subtract3();
test_subtract4();
return 0;
}
How to compile the program:
1- copy the three above files to a new directory (say c_big_int)
ls -l
-rw-r--r-- 1 mhewedy mhewedy 4858 2011-04-05 22:41 main.c
-rw-r--r-- 1 mhewedy mhewedy 4440 2011-04-05 22:41 BigInteger.c
-rw-r--r-- 1 mhewedy mhewedy 712 2011-04-05 22:40 BigInteger.h
2- compile the BigInteger.c
cc -c BigInteger.c
3- make sure that the compilation process generated the object file:
ls -l
-rw-r--r-- 1 mhewedy mhewedy 3180 2011-04-05 22:48 BigInteger.o
-rw-r--r-- 1 mhewedy mhewedy 4858 2011-04-05 22:41 main.c
-rw-r--r-- 1 mhewedy mhewedy 4440 2011-04-05 22:41 BigInteger.c
-rw-r--r-- 1 mhewedy mhewedy 712 2011-04-05 22:40 BigInteger.h
4- Let's generate the binary file:cc -o main main.c -L. BigInteger.o
5- Now you can run the program using the following command:
./main
**EDIT** The code has been reformatted, if it is no longer working please let me know in the comments
20 July 2010
Some notes on pointers in C
Note the following simple program and Its output on GCC 3.2.3:
The output is:
So, when you declare a pointer, it points to some garbage data.
When you malloc memory, the pointer points to some memory-allocated location.
When you assign NULL to a pointer, it becomes NULL Pointer and its address is NULL, and you need to reallocate memory for before use.
So,
#include
#include
int main(void)
{
int *p;
printf("%p %i\n",p, *p);
int *p2 = malloc(sizeof(*p2));
printf("%p %i\n",p2, *p2);
int *p3 = NULL;
printf("%p \n",p3);
p3 = malloc(sizeof(*p3));
printf("%p %i\n",p3, *p3);
return 0;
}
The output is:
0x8048414 1474660693
0x8d3d008 0
(nil)
0x8d3d018 0
So, when you declare a pointer, it points to some garbage data.
When you malloc memory, the pointer points to some memory-allocated location.
When you assign NULL to a pointer, it becomes NULL Pointer and its address is NULL, and you need to reallocate memory for before use.
So,
Newton-Raphson Method to Compute the Square Root in C
#include
#include
float square_root(float);
int main(void)
{
printf("square_root of %f is %f\n", 9.0, square_root(9.0));
return 0;
}
/*Newton-Raphson Method to Compute the Square Root of x*/
float square_root(float n)
{
const float epsilon = 0.00001;
float guess = 1.0;
while (fabs(guess*guess - n) >= epsilon)
guess = (n/guess + guess)/2.0;
return guess;
}
15 July 2010
Be ware when using macros
//avg_float.c
#include <stdio.h>
#define LENGTH (sizeof(d_arr)/sizeof(double))
//#define LENGTH sizeof(d_arr)/sizeof(double) // what would happen if we use this LENGTH macro ??
int main(void){
double d_arr[] = {10.50, 3.30, 50.32, 12.53, 23.3, 345.65, 434, 3.12}, ret=0.0;
int i;
for (i=0; i<LENGTH; i++)
ret += d_arr[i];
printf("%lf\n", ret/LENGTH);
return 0;
}
02 July 2010
final varaibles in Java and its relation to const in C
Hi folks,
Java uses the keyword `final` with variables in indicate that this variable is a constant.
ex1:
final int x = 10;
The above line means x is a constant of type `int` that its value cannot be altered.
ex2:
final Employee e = new Employee("Ahmed");
The above line means e is a constant of type `Employee` that its value cannot be altered.
So, the following line will not compile:
e = new Employee("Mohammed"); // compile error
But the following line will successfully compile:
e.setName("Ali");
Let's derive something:
For primitive, final is a keyword that ensure that the value of the primitive will never change.
For references, final is a keyword that ensure that the variable name cannot be reassigned to any other objects any more.
But, In C:
When we say:
//we define a pointer of type x, that its value cannot change.
int y=100;
const int* x = NULL;
*x = 20; // will not compile
x = &y; // will compile
but, when we say:
int y=100;
int* const x = malloc(sizeof(int*));
*x = 20; // will compile
x = &y; // will not compile
we define a pointer of type x, which that address its points to cannot change.
Conclusion:
So, We can say that, `final` in java with reference types act the same behavior of constant pointers in C (not value pointers). i.e. we cannot make it to refer (point) to another object, but we can change it's value.
Java uses the keyword `final` with variables in indicate that this variable is a constant.
ex1:
final int x = 10;
The above line means x is a constant of type `int` that its value cannot be altered.
ex2:
final Employee e = new Employee("Ahmed");
The above line means e is a constant of type `Employee` that its value cannot be altered.
So, the following line will not compile:
e = new Employee("Mohammed"); // compile error
But the following line will successfully compile:
e.setName("Ali");
Let's derive something:
For primitive, final is a keyword that ensure that the value of the primitive will never change.
For references, final is a keyword that ensure that the variable name cannot be reassigned to any other objects any more.
But, In C:
When we say:
//we define a pointer of type x, that its value cannot change.
int y=100;
const int* x = NULL;
*x = 20; // will not compile
x = &y; // will compile
but, when we say:
int y=100;
int* const x = malloc(sizeof(int*));
*x = 20; // will compile
x = &y; // will not compile
we define a pointer of type x, which that address its points to cannot change.
Conclusion:
So, We can say that, `final` in java with reference types act the same behavior of constant pointers in C (not value pointers). i.e. we cannot make it to refer (point) to another object, but we can change it's value.
Subscribe to:
Posts (Atom)