stackoverflow1453

Programming&&Games&&Life

Archive for June, 2013

Jiro Dreams of Sushi (very inspiring documentary about a shokunin doing the same job for 75 years!)

Music in the beginning:
Beethoven symphony No.7 Poco sostenuto, vivace

Output an array using array and pointer offset and subscript notations

/*
Name:
Copyright: Deitel C How to Program
Author: StackOverflow1453
Date: 6/28/2013 10:34:58 AM
Description:
Using subscripting and pointer notations with arrays 
	 output array b using array subscript notation 
	 output array b using array name and pointer/offset notation 
	 output array b using bPtr and array subscript notation 
	 output array b using bPtr and pointer/offset notation 

*/

#include <stdio.h>
int i;

int main(void){

	int b[]={10,20,30,40};
	int *bPtr=b;
	
	printf("Output array b using array subscript notation\n");
	for (i = 0; i < 4; i++)
	{
		printf("b[%d]=%d\n", i, b[i]);
	}

	printf("Output array b using array name and pointer/offset notation\n");
	for (i = 0; i < 4; i++)
	{
		printf("*(b+i)=%d\n", i, *(b+i));
	}

	printf("Output array b using bPtr and array subscript notation\n");
	for (i = 0; i < 4; i++)
	{
		printf("bPtr[i]=%d\n", i, bPtr[i]);
	}

	printf("Output array b using bPtr and pointer/offset notation\n");
	for (i = 0; i < 4; i++)
	{
		printf("*(bPtr+i)=%d\n", i,*(bPtr+i));
	}
	return 0;
}

How to use sizeof operator?

#include <stdio.h>

int main(void){

	char array[20];
	char dummy='k';

	printf( "\nSize of total array is %d bytes.\n", sizeof(array) );  //OUTPUT: 20
	printf( "Size of array[0] is %d\n", sizeof(array[0]) );	//OUTPUT: 1
	printf("Size of &array[0] is %d\n", sizeof(&array[0]) );	//OUTPUT: 4 (because &array[0] is a pointer to char (char *))
	printf("Size of (char *) is %d\n", sizeof(char *) );	    //OUTPUT: 4
	printf("Size of 'a' is %d.\n",sizeof('a'));	//OUTPUT: 4 (A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.)
	printf("Size of dummy is %d.\n",sizeof(dummy));  //OUTPUT: 1 
	
}

C Constant Pointers and Pointer to Constants

Constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable

int * const ptr;

#include<stdio.h>

int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
}

In the above example :

We declared two variables var1 and var2
A constant pointer ‘ptr’ was declared and made to point var1
Next, ptr is made to point var2.
Finally, we try to print the value ptr is pointing to.
So, in a nutshell, we assigned an address to a constant pointer and then tried to change the address by assigning the address of some other variable to the same constant pointer.

Lets now compile the program :

$ gcc -Wall constptr.c -o constptr
constptr.c: In function main:
constptr.c:7: error: assignment of read-only variable ptr

So we see that while compiling the compiler complains about ‘ptr’ being a read only variable. This means that we cannot change the value ptr holds. Hence we conclude that a constant pointer which points to a variable cannot be made to point to any other variable.

Pointer to Constant

As evident from the name, a pointer through which one cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value kept at those address.

const int* ptr;

Lets take a small code to illustrate a pointer to a constant

#include<stdio.h>

int main(void)
{
    int var1 = 0;
    const int* ptr = &var1;
    *ptr = 1;
    printf("%d\n", *ptr);

    return 0;
}

In the code above :

We defined a variable var1 with value 0
we defined a pointer to a constant which points to variable var1
Now, through this pointer we tried to change the value of var1
Used printf to print the new value.
Now, when the above program is compiled :

$ gcc -Wall constptr.c -o constptr
constptr.c: In function main:
constptr.c:7: error: assignment of read-only location *ptr

So we see that the compiler complains about ‘*ptr’ being read-only. This means that we cannot change the value using pointer ‘ptr’ since it is defined a pointer to a constant.

Constant Pointer to a Constant

If you have understood the above two types then this one is very easy to understand as its a mixture of the above two types of pointers. A constant pointer to constant is a pointer that can neither change the address its pointing to and nor it can change the value kept at that address.

A constant pointer to constant is defined as :

const int* const ptr;

Lets look at a piece of code to understand this :

#include<stdio.h>

int main(void)
{
    int var1 = 0,var2 = 0;
    const int* const ptr = &var1;
    *ptr = 1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
}

In the code above :

We declared two variables var1 and var2.
We declared a constant pointer to a constant and made it to point to var1
Now in the next two lines we tried to change the address and value pointed by the pointer.
When the code was compiled :

$ gcc -Wall constptr.c -o constptr
constptr.c: In function main:
constptr.c:7: error: assignment of read-only location *ptr
constptr.c:8: error: assignment of read-only variable ptr

So we see that the compiler complained about both the value and address being changed. Hence we conclude that a constant pointer to a constant cannot change the address and value pointed by it.

Source: http://www.thegeekstuff.com/2012/06/c-constant-pointers/

C: const and static keywords

const int x = 42;

declares a constant integer variable. It means it’s value can’t be modified. It’s value is initially assigned to 42.
If you try to change its value later, the compiler will issue a warning, or an error, depending on your compiler settings.
So the following statement is invalid:

const int x = 42;
x           = 43;

That’s pretty easy to understand.
The problem comes with pointers.
Let’s take a look at the following code:

char * str = "hello, world";

It declares a ‘char’ pointer. Ok… But then what about this:

char * const str = "hello, world";

or

const char * str = "hello, world";

Now read carefully.
The first one declares a constant pointer to a char.
It means the the characters of the string can be modified, but not the pointer value.
So the variable ‘str’ cannot be assigned to another pointer.
For instance, this is invalid:

char * hello     = "hello, universe";
char * const str = "hello, world";
str              = hello;

as your a modifying the pointer value (not the string value).
This is valid:

char * const str = strdup( "hello, world" );
str[ 0 ]         = 'a';

The ‘str’ variable will then contain ‘hello, world’. Remember: the pointer can’t be modified, the value that is pointed can be.
It’s the exact opposite with the following notation:

const char * str = "hello, world";

Here, you can assign the pointer to another variable, but you can’t change the value.
The ‘const’ keyword is contextual, in a way, when using pointers. It can apply to the pointer itself, or to the value pointed.
So, in order to resume:

const int * x;

A modifiable pointer to a constant integer.

int * const x;

A constant pointer to an modifiable integer.

const int * const x;

A constant pointer to a constant integer.
static
The static keyword can have two meanings.
First of all, it can be declared inside a function.
Let’s take a look at this example:

#include <stdio.h>

void foo( void );
void bar( void );

void foo( void )
{
    int x = 0;
    
    printf( "X - foo: %i\n", x );
    
    x++;
}

void bar( void )
{
    static int x = 0;
    
    printf( "X - bar: %i\n", x );
    
    x++;
}

int main( void )
{
    foo();
    foo();
    foo();
    bar();
    bar();
    bar();
    
    return 0;
}

The output will be:

X - foo: 0
X - foo: 0
X - foo: 0
X - bar: 0
X - bar: 1
X - bar: 2

Because a simple local variable, as in the ‘foo’ function, only exists when the function is called. It’s destroyed (to be simple) when the function exits.
So for the ‘foo’ function, the variable is created each time the function is called, with a value of ‘0’. The value is printed, then incremented.
The function then exit, and the variable is destroyed.
But in the ‘bar’ function, the variable is declared as static. It means the value will persist across function calls.
It’s initialized the first time the function is called, but only at that time. Once it has been initialized, it just exist, so its value will be taken for the next function calls.
Now the ‘static’ keyword as a completely different meaning when used in a variable declared outside of a function (in the global scope).
It means that the variable will be «file scoped». In other words, the variable, which is global, will be accessible only from the scope of the file which declared it. It won’t be accessible from other files.
It’s just a way to create global private variable.
For instance, imagine a file called ‘foo.c’:

int        x = 42;
static int y = 42;

From a ‘bar.c’ file, you’ll be able to access the ‘x’ symbol, if both files are linked together. But you won’t be able to access the ‘y’ symbol, as it’s decaled as ‘static’.
It means that the symbol for the ‘y’ variable won’t be exported by the linker, when the symbol for the ‘x’ variable will be.
In other words, you’ll be able to access the ‘y’ global variable only from function declared in the ‘foo.c’ file. The ‘x’ variable will be also accessible from other files.
Of course, the ‘static’ keyword can be combined with const.
For instance:

static const int * const y;

A constant pointer to a constant integer, that will be accessible only from the file which declared it.

Source: http://www.noxeos.com/2011/07/29/c-const-static-keywords/

Converting a String to Uppercase Using a Non-Constant Pointer to Non-Constant Data

/*

Name:
Copyright: Deitel C How to Program
Author: StackOverflow1453
Date: 6/24/2013 9:40:27 PM
Description:
Converting a String to Uppercase Using a Non-Constant Pointer to Non-Constant Data

*/
#include <stdio.h>
#define SIZE 150 

void toUpperCase(int *charPtr);
int i=0;

int main(void){

	int k=0;
	char c[SIZE]={"This is a string."};
	printf("\nThe string before conversion is %s",c);
	toUpperCase(c);
	printf("\nThe string after conversion is %s",c);
		
	getch();
}
//function converts lowerCase to upperCase
void toUpperCase(char *charPtr){
	while (*charPtr!='')
	{
		if ( (*charPtr)>=97 && (*charPtr)<=122 ) //ASCII conversion to UpperCase
		{
			*charPtr-=32;
		}
		charPtr++; //increments the address
	}

}

Difference between i++ and ++i

#include <stdio.h>

int main(void){

	int i=5,k;

	int a=i++;
	printf("a=i++ result is a: %d, i: %d\n",a,i);
	
	// a=5, i=6
	
	i=5;
	int b=++i;
	printf("b=++i result is b: %d, i: %d\n", b, i);

	// b=6, i=6

	i=5;
	i++;
	printf("i is %d after i++\n",i);

	// i = 6
	i=5;
	++i;
	printf("i is %d after ++i\n",i);
	
	//i = 6

	i=5;
	k=i++ + ++i;
	printf("after k=i++ + ++i, k is %d, i is %d\n",k,i);

	//k = 12, i = 7

	getch();
}