rss search

next page next page close

C Pointers

There are certain tasks in c what can only be done with pointers like reading from a file requires a file pointer. Also to have a stable knowledge of pointers can give a great confidence to start improving the memory usage with decreasing the value duplications in programs.
A pointer is an address of a memory location where an actual value is stored. Every variables memory location can be accessed by using the ‘&’ am-percent. The asterisk’*’ is used to mark a variable as pointer. Pointers can point to pointer in any level, but in most cases there is not really a logical need to go more then pointer, to pointer depth. Pointer to pointer would be declared as ‘**’ and in that case to access the value at the pointer-pointer we have to use ‘*’ instead of ‘&’.
All pointers can only point to the same type, double pointer to a double variable, int pointer to int or int array.

   
   int myNum = 1;
   int *myNumPtr = &myNum; 

   printf("%d", &myNum);
   printf("%d", myNumPtr);//this also shows that printf takes a pointer not a value

C pointers can be declared as NULL if you don’t know what the memory location will be at the time but you know that you will have to use it later on.

   int myInt = 1;
   int *prtInt = NULL;
   ...
   if(!myInt)//if it is null if(myInt != NULL)
      ptrInt = &myInt;

next page next page close

Array in C

Arrays in any programming language is one of the “power tools” you can use to organize data of same type. On the positive side elements of an array can be accessed in constant time because of the maintained indexes. On the downside array is fixed size and taking space after each other in memory which is not to efficient.
Array declaration and accessing elements works as in other languages, with an example:

main(){
   int myInts_1[5];//declaring a 5 element int array without initialization
   int myInts_2[] = {0, 1, 2, 3, 4};//with initialization this could be done as {0} to init all to 0
   int my2dArr[2][3] = {
                         {1,2,3},
                         {4,5,6},
                       };//this is a 2d array with 3 elements on each level 

   //accessing the elements   
   myInts_1[0] = myInts_2[0];
   printf("%d", &my2dArr[1][1]);//this would print 5
}

The first element of an array is at 0 and the last element is at the array size-1. In newer languages there are all sorts of ways to write a loop which does “touch” all elements, like foearch. Implementing the same into c is tricky. An easy way to go around the problem of not knowing the array size is declare a constant array size an loop until that size -1. If for other reasons you cant implement constants, dividing the size of an array with element 1 gives the size. There is an advanced way of implementing foreach with macro which is really limited to a type or to a structure/union(can’t be used randomly for any type) so I am not going to cover it.
A basic example:

    ...
    unsigned int n = sizeof(theArray)/sizeof(theArray[0]);//n will hold the size of the array
    ...

Array in c can be combined with pointer to access the elements in a less memory consuming way. This could be useful when passing large arrays, where pointer is taking way less memory as passing a copy of all elements. Keep in mind that passing pointer as parameter modifies the original value where the pointer points to, inside the function.


next page next page close

C Structure Basics

Structures in c are used to represent data what have connections to each other in a single variable. This could be a record from a database.

Structures can be declared outside the functions to give access for all the function in the program. Other options for declaration is in the main header file(good idea), or inside main or other function which would make it available only for local use. A good practice is to not only declare the structure by create a type of that structure. This can make the code more compact and readable at the same time. With other words we can create an alias for structure.
With an example:

//creating a student type
typedef struct student_record STUDENT;
//general structure declaration
struct student_record{
    unsigned int id;
    char *firstName;
    char *lastName;
};

To use the student_record structure:

main(){
   STUDENT firstStudent = {1, "John", "Doe"};//using the alias
   student_struct secondStudent = {0};// initializing all to 0 where char will be null

   firstStudent.id = 777;
   firstStudent.firstName = "Jane";//use the dot(.) notation for access the elements of structure
}

A more advanced way of using structs is by implementing pointers, where the same pointer rules apply as with other variable types like pointer can only be of type it points to etc. There are two ways to access structure pointer elements, pointer element with dot notation or the arrow notation.
With an example:

main(){
   STUDENT firstStudent = {0};
   STUDENT *ptrFirstStudent = &firstStudent;

   (*ptrFirstStudent).id = 777;
   ptrFirstStudent->firstName = "Jane";
}

/*struct_function: just showing how to pass, and access pointer structure elements*/
void struct_function(STUDENT *ptrFS){
    (*ptrFirstStudent).id = 777;
   ptrFirstStudent->firstName = "Jane";
}

To understand c structure basics you should have an understanding of pointer, arrays. You can find articles about these topics in the C category.


next page next page close

Start learning C programming

I think to have a decent understanding of c, or start learning c programming  is really good even if somebody is not planning to work with the language itself. Most of the languages are based on c or are in some way related to it. Most of the currently used popular languages have at least the syntax related to c.


The C Programming Language, 2nd Edition

This book can give a really great start on understanding and writing basic c functions. It has exercises what are really handy, I actually wrote them all what gave me a great advantage in college projects. There are cases when you find yourself stuck at few of them but there are many solutions available only. It can also give a different view for those who already know the language.


next page next page close

C primitive data types

In the C programming language variables are declared before the program itself starts, before functionality. This applies to functions also.
With an example:

main(){
     int iCnt = 0;
     int iValue = myFunc();
}//end main
int myFunc(){
     return 1;
}//end myFunc

 

The following program declares c primitive data types and pointer data types and does print the size for them too.

// variableSizes.c
// This is a simple c to write out variable sizes

#include <stdio.h>
#include <stdlib.h>

main(){

	char chTest = 'c';
	char chPrt = &chTest;

	short shTest = 1;
	short shPtr = &shTest;

	int iTest = 1;
	int iPtr = &iTest;

	long lTest = 1l;
	long lPtr = &lTest;

	long long llTest = 1l;
	long long llPtr = &llTest;

	float fTest = 0.1;
	float fPtr = fTest;

	double dTest = 0.1;
	double dPtr = dTest;

	long double ldTest = 0.1l;
	long double ldPtr = ldTest;

	puts("C language data sizes\n==============================\n");
	printf("char in bytes: %d\n", sizeof(char));
	printf("short in bytes: %d\n", sizeof(short));
	printf("short int in bytes: %d\n", sizeof(short int));
	printf("int in bytes: %d\n", sizeof(int));
	printf("long in bytes: %d\n", sizeof(long));
	printf("long long in bytes: %d\n", sizeof(long long));
	printf("float in bytes: %d\n", sizeof(float));
	printf("double in bytes: %d\n", sizeof(double));
	printf("long Double in bytes: %d\n", sizeof(long double));
	puts("\n==============================\n\n");

	puts("C language data sizes\n==============================\n");
	printf("char in bytes: %d\n", sizeof(&chPrt));
	printf("short in bytes: %d\n", sizeof(&shPtr));
	printf("int in bytes: %d\n", sizeof(&iPtr));
	printf("long in bytes: %d\n", sizeof(&lPtr));
	printf("long long in bytes: %d\n", sizeof(&llPtr));
	printf("float in bytes: %d\n", sizeof(fPtr));
	printf("double in bytes: %d\n", sizeof(dPtr));
	printf("long Double in bytes: %d\n", sizeof(ldPtr));
	puts("\n==============================\n\n");

	system("pause");

}//end main()

next page next page close

C typedef basics

If c is not your first language, you will really miss boolean primitive type. In other languages boolean is already defined, but in c there is no such type, it is actually using integer values instead.

It is really simple to implement a boolean value with typedef:

typedef enum { false, true } boolean;

Other option is to include stdbool.h.

Using typedef as an alias makes code more readable.

typedef data_struct Date;
typedef employee_struct Emp;

struct date_struct{
    unsigned short day;
    unsigned short month;
    unsigned short year;
};

struct employee_struct{
    char first_name[255];
    char last_name[255];
    Date hire_date;//note the use of typedef
};

//function definition
void setHireMonth(Emp *);
main(){
    Emp employee_1 = {0};
    //accessing the values goes in the same way
    employee_1.hire_date.day = 1;
    setHireMonth(&employee_1);
}

void setHireMonth(Emp *ptrEmp){
    puts("Please give hire month for employee");
    scanf("%d", &ptrEmp->hire_date.month);
}

The example above shows that accessing the values is along the same rules as using struct.


next page next page close

Study guide – PHP

PHP & MySQL: Novice to Ninja

If you are planning to start learning php, PHP & MySql novice to ninja by Kevin Yank is a really good book to start with. You can make start mastering the language without knowing to much of dynamic web development. The book is going to show good practices on basic security as it does of smart reusable functions.  It also gives nice practical implementation to hide file extension(and executed file) without the need of apache mod_rewrite.


next page next page close

Stored procedures in MySQL

Stored procedures in MySQL can encapsulate statements which can be used later. I think the real power of using stored procedures is in the amount of time can be saved by using one line against maybe dozens of insert, delete etc.

Benefits of Stored Procedures in MySQL:

  •  Stored Routines can be created with error handlers.
  • Code packaging and encapsulation
  • Separation of the logic
  • Reduction of network bandwidth
  • Security by giving access to a specific routine handling the data.

A procedure can be invoked with a CALL statement to “execute” the encapsulated statements which can modify tables or retrieve data. The procedure can have input, output and both in and output parameters. In other words we can send values to be modified or write to tables within the procedure.

A simple Stored Procedure:

delimiter //
create procedure myProc( vin int)
begin
insert into someTable values(vin);
end;
//
delimiter ;

When we want to create a procedure we always need to start end finish with setting the default delimiter. This is necessary because the procedure has executable statements to run so those are finished with ‘;’. If new delimiter is not set for creation time MySQL will try to run when the first ‘;’ is written in followed by a ‘return’. Delimiter can be any character but it’s good practice to use double charasters such as ‘$$’,’//’ etc.
Another must is to specify the statements we want to run, between a ‘begin’ and ‘end’ keyword. This is called the routine body. Procedure can have many levels of ‘begin & end’, in this case we need to give unique names to every level like ‘inner_block: begin … end inner_block’.

...
begin
inner_block: begin
if dayname(now()) = 'Sunday' then
leave inner_block;
end if;
select 'Today is not Sunday';
end inner_block;
end;

Declaring parameters and DECLARE statement

Parameter declaration is useful because variables can be used inside rather than hard-coded values. The type of value need to be specified always, what value to ‘listen’ for eg.: int, varchar etc. As mentioned above we can have 3 types:

  • IN – indicates an input parameter, this is the default if non specified. The value is passed in from the caller.
  • OUT – indicates an output parameter. Any value is ignored from the caller it’ null until the procedure set’s a value, this can be send back to the caller.
  • INOUT – in and output at the same time.

DECLARE statement is used for declare several types of items:

  • Local Variables
  • Conditions (Warning or Exceptions)
  • Handlers for conditions
  • Cursors
declare i int default 0;

next page

C Pointers

There are certain tasks in c what can only be done with pointers like reading from a file requires a file pointer. Also to have a stable knowledge of pointers can give a great confidence to start improving the memory usage with decreasing the value duplications in programs. A pointer is an address of a memory location where an actual value is stored. Every variables memory location can be accessed by using the ‘&’ am-percent. The asterisk’*’ is used to mark a variable as pointer. Pointers can point to...
article post

Array in C

Arrays in any programming language is one of the “power tools” you can use to organize data of same type. On the positive side elements of an array can be accessed in constant time because of the maintained indexes. On the downside array is fixed size and taking space after each other in memory which is not to efficient. Array declaration and accessing elements works as in other languages, with an example: main(){ int myInts_1[5];//declaring a 5 element int array without initialization int myInts_2[] = {0, 1, 2, 3,...
article post

C Structure Basics

Structures in c are used to represent data what have connections to each other in a single variable. This could be a record from a database. Structures can be declared outside the functions to give access for all the function in the program. Other options for declaration is in the main header file(good idea), or inside main or other function which would make it available only for local use. A good practice is to not only declare the structure by create a type of that structure. This can make...
article post

Start learning C programming

I think to have a decent understanding of c, or start learning c programming  is really good even if somebody is not planning to work with the language itself. Most of the languages are based on c or are in some way related to it. Most of the currently used popular languages have at least the syntax related to c. The C Programming Language, 2nd Edition This book can give a really great start on understanding and writing basic c functions. It has exercises what are really handy, I...
article post

C primitive data types

In the C programming language variables are declared before the program itself starts, before functionality. This applies to functions also. With an example: main(){ int iCnt = 0; int iValue = myFunc(); }//end main int myFunc(){ return 1; }//end myFunc   The following program declares c primitive data types and pointer data types and does print the size for them too. // variableSizes.c // This is a simple c to write out variable sizes #include <stdio.h> #include <stdlib.h> main(){ char chTest = 'c'; char chPrt = &chTest; short shTest...
article post

C typedef basics

If c is not your first language, you will really miss boolean primitive type. In other languages boolean is already defined, but in c there is no such type, it is actually using integer values instead. It is really simple to implement a boolean value with typedef: typedef enum { false, true } boolean; Other option is to include stdbool.h. Using typedef as an alias makes code more readable. typedef data_struct Date; typedef employee_struct Emp; struct date_struct{ unsigned short day; unsigned short month; unsigned short year; }; struct employee_struct{...
article post

Study guide – PHP

PHP & MySQL: Novice to Ninja If you are planning to start learning php, PHP & MySql novice to ninja by Kevin Yank is a really good book to start with. You can make start mastering the language without knowing to much of dynamic web development. The book is going to show good practices on basic security as it does of smart reusable functions.  It also gives nice practical implementation to hide file extension(and executed file) without the need of apache...
article post

Stored procedures in MySQL

Stored procedures in MySQL can encapsulate statements which can be used later. I think the real power of using stored procedures is in the amount of time can be saved by using one line against maybe dozens of insert, delete etc. Benefits of Stored Procedures in MySQL:  Stored Routines can be created with error handlers. Code packaging and encapsulation Separation of the logic Reduction of network bandwidth Security by giving access to a specific routine handling the data. A procedure can be invoked with a CALL statement to “execute”...
article post