Friday, January 7, 2011

some stuff

// my sizeof using pointers


union MyStruct
{
int i;
int j;
char a;
};
int main()
{
union MyStruct *p=0;
int size = ((char*)(p+1))-((char*)p);
printf("\nSIZE : [%d]\n", size);
char *a;
printf("Size of int is %d\n",(char*)(a+1)-(char*)a);
return 0;
}


//intresting stuff


#include
int main(void)
{
printf("%c","abc"[1]);
return 0;
}

Thursday, January 6, 2011

my stuff

BIG or little endian


#include

int main()
{
int n = 1;
if(*(char*) &n = 1)
{
printf("LE");
}
else
printf("HE");
}

Tower of hanio baby


#include

void tower(int n, char from, char to, char center)
{
tower(n-1,from,center, to);
tower(n-1,center,to,from);
}
int main()
{
int f,t,c;
tower(4, f, t ,c);
}

my strcpy

#include
char* mystrcpy(char* dest, const char* src)
{
char* temp;
temp = dest;
while(*dest++ = *src++);
return temp;
}
int main()
{
char* s = "wazzup";
char* r;
printf("%s",s);
printf("after copying %s\n",mystrcpy(r,s));
return 0;
}

my atoi

#include

int myatoi(char* string)
{
int value = 0;
if(string)
{
while(*string && *string>='0' && *string<='9')
{
value = value*10 + (*string - '0');
string++;
}
}
return value;
}
int main()
{
printf("char value is %d\n","1989");
printf("int value is %10d\n",myatoi("1989"));
return 0;
}

Wednesday, January 5, 2011

my C++ rough work

// Testing friend function


#include

class sum
{
private:
int i;
friend void square(sum s);
sum()
{
i = 1;
}
public:
sum(int j)
{
i = j;
}

void get()
{
cout << i;
}

};

void square(sum s)
{
s.i = s.i*s.i;
cout << s.i;
}
int main(){
sum s(3);

square(s);
s.get();
}


sprintf

#include
int main()
{

char buff[24];

int ret,i, a = 34, b = 234;

ret = sprintf(buff, "%d minus %d equals %d",a,b,a-b);

printf ("(%s) is the result and is %d characters\n",buff,ret);

for(i = 0; i<24;i++)
{
printf("value at %d in buff is %c\n",i,buff[i]);
}

return 0;

}
////////////////////////////////////////////////////////////////////////////////


some basics

. has precedence over *. So, while pointing to a member of a structure m with pointer p, we write it as p->m which can also be written as (*p).m . This looks messy so people prefer writing p->m.
*p1 = *p2 copies the structure pointed by p2 into that of p1, but
p1 = p2 makes p1 to point to the structure pointed by p2.

Now,
lets build a linked list dynamically.


void add(char * item, struct list *oldhead)
{
struct list *new = malloc(sizeof(struct list));
if(new == NULL)
{
printf("out of mem\n");
exit(1);
}
new->item = item;
new->next = oldhead;
head=new;
}

int main()
{

struct list
{
char *item;
struct list *next;
};

struct list *head = NULL;
add("hi",head);

}

BTW this piece of C code interested me


#include
int main()
{
int width = 9;
printf("%10d\n",1);
printf("%*d",width,1);
}

Mainly using a * before d to decide the width run time.

printf vs fprintf

printf prints output in STDOUT whereas fprintf we can print in user defined stream
for ex:
FILE *f = fopen("hi.txt","w");
fprintf(f,"%s","Hello");