Monday, October 19, 2015

Using Pointers


USING POINTERS

This example program shows a pointer being used to swap between two floating point values. The actual manipulation of the floating point values is done within the function get_value, which doesn't have any parameters. I decided that I would do it by reassigning a pointer within the main program.

#include <stdio.h>

/* The pointer has to be declared here so that */
/* the function get_value can get access to it. */
float *my_point;

/* The floating point variables have to be */
/* declared here so that function display_values */
/* can access them.*/
float x = 36.3, y = -100.44;

int main ()
 { display_values();
   my_point = &x;    // Points to x
   get_value();
   my_point = &y;    // Points to y
   get_value();
   display_values();
   return 0;
 }

void get_value ()
 { float decimal_number;
   printf(\n "Please enter a number : \n");
   scanf(“%f”,decimal_number);
   *my_point = decimal_number;
 }

void display_values ()
 { printf("\nThe value of x is %f \n",x);
   printf("\nThe value of y is %f \n",y);
  
 }


The value of x is 36.3
The value of y is -100.44

Please enter a number : 2.1
Please enter a number : 3.1
The value of x is 2.1
The value of y is 3.1
_____________________________________________________________________________________________
I thought it might be interesting to see what the address of a variable is. Here I have declared three
unsigned long values together with a pointer that moves between them. In each case, the address that the pointer is pointed to is displayed.

#include <stdio.h>

int main ()
  { unsigned long a = 1, b = 2, c = 3, *p;

    p = &a;
    printf("\nThe address of a is %X\n",p);
    printf("\nThe value of a is %d\n",*p);

    p = &b;
    printf("\nThe address of b is %X\n",p);
    printf("\nThe value of b is %d\n",*p);

    p = &c;
    printf("\nThe address of c is %X\n",p);
    printf("\nThe value of c is %d\n",*p);
       
    return 0;
  }

The address of a is 0x3c27245e
The value of a is 1
The address of b is 0x3c27245a
The value of b is 2
The address of c is 0x3c272456
The value of c is 3
____________________________________________________________________________________________

This function is used to sort arrays of integers. The array itself is specified as a pointer. However, the routine doesn't know in advance how many elements the array will have, so that must also be passed across as an (ordinary) parameter.

void sort (*int array, int num_elements)
 { int i, j;
   int *temp;  /* Used in swopping array values */
   for (i = 0; i < num_elements; i++)
    for (j = 0; j < num_elements-1; j++)
     if (*(array+j) > *(array+j+1))
      { temp = *(array+j);
        *(array+j) = *(array+j+1);
        *(array+j+1) = temp;
      }
 }
You will see that the pointer to the array is simply declared as a pointer to an integer. You would have no way of knowing just by looking at the first line of the function that the pointer indicated an array rather than a simple integer (other than the fact that the pointer is called array, of course, which is something of a giveaway!)
The array elements are referred to using the pointer. *(array+j) refers to element array[j] etc.


Check out the program without functions:
Sorting an array would involve swapping the elements as necessary, until they are all in ascending or descending order. There are different sorting methods (called algorithms) and this worked example demonstrates what is probably the simplest sorting algorithm - Bubblesort.
Bubblesort is so-called as the largest elements of the array move gradually to the end like bubbles rising to the surface in a glass of fizzy drink. It is usually the slowest sorting algorithm (although it can take advantage of array elements which have been partially sorted already). The algorithm goes as follows:
Assume N is the number of elements in the array.

Go through the elements from 1 to N-1
   Look at the current element and the next one.
   Are they out of order? If so, swop them.
   At the end of the run, the largest element will have
        "bubbled" to the end of the array.
Repeat this process N times.
Here is the code. Go through it matching it line-by-line with the algorithm above.
#include <stdio.h>
int main ()
 { int x[11];     /* Set up an array of 11 values */
   x[0] = 74;  x[1] = 23;  x[2] = 91;  x[3] = 58;
   x[4] = 52;  x[5] = 60;  x[6] = 30;  x[7] = 19;
   x[8] = 28;  x[9] = 46;  x[10] = 37;

   int i,j;   /* These are used as loop variables */
   int temp;  /* Used in swopping the values */

   printf("\nBefore the sort, the values are \n");
   for (i = 0; i <= 10; i++)
     printf(“x[%d] = %d\n”,i,x[i]);

   for (i = 0; i < 11; i++)  /* Go through 10 times */
     for (j = 0; j < 10; j++)  /* Check all elements */
       if (x[j] > x[j+1])       /* except last */
         { temp = x[j];
           x[j] = x[j+1];
           x[j+1] = temp;
         }

   printf("\n\nAfter the sort, the values are \n");
   for (i = 0; i <= 10; i++)
     printf(“x[%d] = %d\n”,i,x[i]);
  
   return 0;
 }
Before the sort, the values are
74 23 91 58 52 60 30 19 28 46 37
After the sort, the values are
19 23 28 30 37 46 52 58 60 74 91

More on Functions


void function

void is a function that has no return value.

/* Prints a bad, I mean really bad, pun. */

#include <stdio.h>

main()
{
            print_pun();
            return 0;
            /* return 0 means end of program */
}

void print_pun(void)
{
            printf(“To C, or not to C:  That is the question. \n”);
}

General Form of Functions


return-type function name (parameters)
{
            declarations
            statements
}

The return type of a fucntion is the type of value that the function returns.  The following rules govern the return type:

·      Functions may not return arrays, but there are no other restrictions on the return type.
·      If the return type is omitted, the function is presumed to return a value type int.
·      Specifying the return type is void indicates that the function doesn’t return a value.

Local Variables
A variable declared in the body of a function is said to be local to the function.  In the following function, log is the local variable:


int log2(int n)
{
            int log = 0;  /* local variable */

            while (n>1) {
                        n /= 2;
            log++;
              }
            return log;
}

By default, local variables have the following properties:
·      Automatic storage duration.  The storage duration (or extent) of a variable is the portion of program execution during which storage for the variable exists.  Storage for a local variable is automatically allocated when the enclosing function is called and deallocated when the function returns, so the variable is said to have automatic storage duration.  A local variable doesn’t retain its value when its enclosing function returns.  When the function is called again, there is no guarantee that the variable will still have its old value.
·      Bock scope.  The scope of a variable is the portion of the program text in which the variable can be referenced.  A local variable has block scope:  It is visible from its point of declaration to the end of the enclosing function body only.  Since the scope of a local variable doesn’t extend beyond the function to which it belongs, other functions can use the same name for other purposes.

Global or External Variables
Passing  arguments is one way to transmit information to a function.  Functions can also communicate through global variables – variables that are declared outside the body of any function:

#include <stdio.h>
int x, y;  /* global variables */
double k, z; /* global variables */

main()
{
            declarations
            statements
}

return-type function name (parameters)
{
declarations
statements
}


The properties of global variables are different from those of local variables:
·      Static storage duration.  A value stored in a global variable wil stay there indefinitely until program termination.
·      File scope.  A global variable has file scope:  It is visible from its point of declaration to  the end of the enclosing file.  As a result, a global variable can be accessed by all functions that follow its declaration.

Pros and Cons of Global Variables

In most cases, it is better for functions to communicate through parameters rather than by sharing values.  Here’s why:
·      If we change a global variable during program modification, we’ll need to check every function in the same file to see how the change affects it.
·      If a global variable is assigned an incorrect value, it may be difficult to identify the guilty function.
·      Functions that rely on global variables are hard to reuse in other programs.  A function that depends on global variables is not self-contained.

Pre-Processor Directives
·      Macro definition.  The #define directive defines a macro; the #undef directive removes a macro definition.
·      File inclusion.  The #include directive causes the contents of a specified file to be included in a program.
·      Conditional compilation.  The #if, #ifdef, #ifndef, #elif, #else, and #endif directives allow blocks of text to be either included in or excluded from a program, depending on conditions that can be tested by the pre-processor.

Simple Macros

The definition of a simple macro has the form

            #define identifier  replacement-list

replacement-list is any sequence of C tokens:  It may include identifier, keyworkds, number, character constants, string literal, operators, and punctuation.  When it encounters a macro definition, the pre-processor makes anote that the identifier represents replacement-list .  Wherever identifier appears later in the file, the pre-processor substitutes replacement-list .

Don’t put any symbols in the macro definition – they’ll become part of the replacement list.  Putting the = symbol in a macro definition is a common error:

            #define N = 100  /*****WRONG!!!*****/

            #define N  100;  /*****WRONG!!! Semi-colon is not supposed to be used*****/

            #define N  100  /** CORRECT**/


Sample good macros:
            #define STR_LEN 80
            #define TRUE 1
            #define pi 3.14159
            #define CR ‘\r’
            #define MEM_ERR “Error:  not enough memory.”

Parameterized Macros

The definition of a parameterized macro has the form

            #define identifier (x1, x2, ..., xn)  replacement-list

Example:

            #define IS_EVEN(n)  ((n)%2==0)

So when
            if (IS_EVEN(i)) i++ ;

appears later in the program, the preprocessor will replace this line with:

            if (((n)%2==0)) i++ ;
           
                                                                       




On Functions


Functions in C

Up to this point, we have described how to use functions, but not how to code them.  It turns out that in C, it’s relatively straightforward to code your own function.  Every function begins with a statement that looks very much like a function prototype.  However, while a function prototype tells the compiler what arguments the function takes and what type of value it returns, the function definition is always followed by the body of the function – the series of variable definitions and statements that do the work of the function.

The following C code implements the function average_ints(), which averages three values of type int and returns their average as a double.

/*Function to average 3 integers */

double average_ints(int i, int j, int k)
 {
double average;
average = (i+j+k)/3.0;
return (average);
}

A few key ideas are illustrated in this example.  Note that the first line of the function defines the type of the value the function returns, in this case, a double.  Like a function prototype, it also defines the types of the arguments.  However, in this case the arguments are given variable names.  These names can then be used in the body of the function.  If you think about what happens when the function average_ints() is invoked, the copies of the arguments can be thought of as being assigned to the variables i, j, and k.   The variables used in this function like i, j, k and average are internal variables.  They are internal variables since they are valid only within the function and are not global.

One of the key features of functions is the use of the return statement.  The return statement allows you to pass the result of a function back to the calling function:  In this case, the main() function. 

/*Another version of average_ints() */

double average_ints(int i, int j, int k)
{
             return ( (i+j+k)/3.0 );
}

So, any C function can be invoked or called by another.  The invoking function may pass information tot he invoked function and the invoked function may return information to its invoker.


A function’s header consists of:
·      Data type returned, or the keyword void if the function does not return a value
·      Function’s name
·      In parentheses, a list of parameters and their types separated by commas, or the key word void if the function has no parameters

Specifying the data type is optional:  If omitted, it defaults to int.  However, it is good practice to always specify the data type.

The special key word void is used to indicate that a function doesn’t return a value or that it doesn’t have any arguments.  For example, the function prototype

            void no_result(double);

declares that no_result() does not return a value.  Similarly, the function prototype

            int no_arguments(void);

indicates that the function returns an integer value but does not have any arguments.

Saturday, October 3, 2015

VNC with the Pi

Step 1: get packages
You’ll need TigerVNC, NetworkManager, network-manager-applet and you’ll need to run a system update and reinstall polkit. It sounds like a lot, but it can all be done in just a few commands:
Reply y when prompted.
pacman –Syu
pacman –S systemd polkit
Reboot (your pi will likely sit there and do nothing for 30 seconds to a minute before it does anything. Reinstalling polkit should fix this once it boots back up)
pacman –S tigervnc networkmanager network-manager-applet

Step 2: configure VNC
As user ME…
vncserver
Enter a password (don’t forget it)
Enter a view only password if you want
vncserver –kill :1
cd ~/.vnc
gvim xstartup

comment out or delete all the if statement lines, starting with "if [ $OS = ‘Linux’ ]” and ending with the “fi" before "[ -r $Home/.Xresources ]"
delete everything after  "xsetroot - solid grey”, then add:

vncconfig -iconic & 
xrdb -merge ~/.Xresources 
startxfce4 &
Save and close

cd ..
chmod 700 ~/.vnc

Step3: configure the system service.
As Root…
cd /usr/lib/systemd/system
gvim vncserver.service
Here we just need to change 3 lines. NOTE: The geometry flag is just the resolution of the monitor that VNC creates, and can be set to whatever you want (1920x1080?).
change "User=" to 
User=me
change: “execstart" and “execstop" to 
ExecStart=/usr/bin/vncserver %i -geometry 1024x768
ExecStop=/usr/bin/vncserver -kill %i -geometry 1024x768
SAVE AS vncserver@:1.service then close

Step4: disable old network service and enable network manager and VNC to run when the Pi starts
As Root…
systemctl disable systemd.networkd
systemctl enable NetworkManager
systemctl enable vncserver@:1.service
reboot

Step5: Wireless and Static IP
See videos. Ignore talking….
The “install network manager and get on wifi” is only relevant now after 2:30

Step6: Connecting via VNC: 
For Macs, they can use the built in screensharing app (it’s not in the applications folder, the easiest way to find it is to search for it in spotlight [command + spacebar on most Macs]). If you don’t want to use that, you can always download another app like ChickenOfTheVNC
For Windows, you will have to download a vnc client app light Tightvnc, RealVNC, or UVNC.

To connect, enter the IP that you chose, then a :, then 5900+the number you chose for the VNC service. Using the instructions above: that would be192.168.0.100:5901. You should be prompted for a the password you created the first time you ran vncserver.