5 System Programming

System Programming

Objective

  • Write, compile, and execute C programs.
  • Strings, arrays, pointers, and structures in C.

cc & * [] \0 0 NULL struct printf() scanf() strcat() strcmp() strcpy() strlen() strlwr() strup()

Getting Started

  1. Edit and save the file: file_name.c
  2. Compile the code using cc file_name.c. The compilation will produce an executable file called a.out by default.
  3. Run the compiled file: ./a.out
  4. You can redirect the output of a.out to another file, using: ./a.out > output.

Note that at the compilation step you can rename a.out using the -o option:

cc file_name.c -o file_name.out

Example 1

  1. Using your editor of choice, type the following C program and save it as example-01.c:
example-01.c
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
  int num1, num2, sum;
  printf("Enter the first number: ");
  scanf("%d", &num1);
 
  /* %d means the type of the identifier, which is an integer */
  /* &num1 means the address of the integer in memory */
 
  printf("Enter the second number: ");
  scanf("%d", &num2);
 
  sum = num1 + num2;
  printf("Sum is %d\n", sum);
 
  return EXIT_SUCCESS;
}
  1. Compile the program using the standard C compiler:
cc example-01.c -o example-01
  1. If there are no errors, you can run the program using:
./example-01

Exercise 1

Write a C program to store 5 array elements and print them on the screen as in the following output:

array[0] = value
array[1] = value
array[2] = value
array[3] = value
array[4] = value

Run your program and save its output to a file.

Strings

Strings are one-dimensional array of characters terminated by a null character \0. Thus a null-terminated string contains the characters that comprise the string followed by the null character.

The following declaration and initialization creates a string consisting of the word Hello. To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word Hello.

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows:

char greeting[] = "Hello";

You do not place the null character at the end of a string constant. The C compiler automatically places the \0 at the end of the string when it initializes the array.

Each character, in the string defined earlier, occupies one byte of memory. The following diagram is the memory presentation of the string "Hello" in C:

012345Hello\0

Example 2

example-02.c
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
  char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
  printf("Greeting message: %s\n", greeting);
  return EXIT_SUCCESS;
}

Example 3

example-03.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void) {
  char str1[13] = "Hello";
  char str2[13] = " world!";
  char str3[13];
  int len;
 
  /* copy str1 into str3 */
  strcpy(str3, str1);
  printf("strcpy(str3, str1): %s\n", str3);
 
  /* concatenates str1 and str2 */
  strcat(str1, str2);
  printf("strcat(str1, str2): %s\n", str1);
 
  /* total length of str1 after concatenation */
  len = strlen(str1);
  printf("strlen(str1): %d\n", len);
 
  return EXIT_SUCCESS;
}

There are many important string functions defined in the <string.h> library. Here are some examples:

FunctionDescription
strlen()Returns the length of a string
strlwr()Converts a string to lowercase
strup()Converts a string to uppercase
strcat()Appends the first n characters of a string at the end of another
strcpy()Copies a string into another
strcmp()Compares two strings

Pointers

  • Pointers are variables that contain addresses of other variables.

  • The & (address) operator returns the memory address of its operand.

  • A pointer is declared as follows:

    int *ptr;
    • This definition is read as *ptr is a pointer to int.

    • The asterisk before the variable name indicates that ptr is a pointer variable, and the int data type indicates that ptr can only be used to point to, or hold addresses of, integer variables; e.g.

      int x; ptr = &x;
    • The asterisk * is called the indirection operator because it allows you to pass from a pointer to the variable being pointed to, e.g. *ptr = 100;

  • There are three values that can be used to initialize a pointer: 0, NULL, or an address of an object of the same type.

  • A function receiving an address as an argument must have a pointer as its corresponding parameter.

Example 4

Run the following program:

example-04.c
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
  int x = 3;
  int *y;
  y = &x;
  (*y)++;
  printf("x = %d\n", x);
 
  return EXIT_SUCCESS;
}

The value of x at the end of the program is ______. Why?

Exercise 2

The following program has an error. Try to figure out the error and fix it.

exercise-02.c
#include <stdio.h>
#include <stdlib.h>
 
void increment(int *);
 
int main(void) {
  int x = 4;
  increment(x);
  printf("x = %d\n", x);
 
  return EXIT_SUCCESS;
}
 
void increment(int *n) { *n = *n + 1; }

Exercise 3

Write a void function swap(int *, int *) that uses pointers to swap the values of two integer variables. Use this function in your main() function to read two integers and swap them. Display the variables after swapping them.

Structures

A structure is a variable in which different types of data can be stored together in one variable name. Structures are used to define new data types using the keyword struct.

The different variable types stored in a structure are called its members. To access a given member the dot notation is use. The dot is officially called the member access operator. Say we wanted to initialize the structure card1 to the two of hearts, it would be done this way:

struct Card {
  int pips;
  char suit[8];
};
 
struct Card card1;
card1.pips = 2;
card1.suit = "Hearts";

Exercise 4

The following table contains the data for some students:

PointsGradeNameID
12AJohn Doe1321
6CDane Doe8765
9BJane Doe1231
  1. Declare a structure called StudentRecord whose members are the column headers in the above table. Choose appropriate data types for each member.
  2. Define three students of type StudentRecord, which are initialized with the data in the above table.
  3. Complete the following function that prints the data for one student in one line; properly spaced.
void print(struct StudentRecord record) {
  •••
}
  1. Using the above function, print the data of each student on a separate line.

Arrays of Structures

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type. Consider the following example:

struct PCB {
  int pid;
  char status[10];
  int pc;
  char reg[5];
  float cpu_time;
};

Here is how we can declare an array of PCB structures:

struct PCB pcbs[5];

Here pcbs[5] is an array of 5 elements where each element is of type struct PCB.

Exercise 5

  1. Modify the solution to Exercise 4 to create an array of structures that stores information of 3 students and prints it
  2. Write a function that computes the average points of the three students and prints it.

Exercise 6

Using the PCB structure above, write an C program to enter the values in the array of structures pcbs[] for five elements and then print the elements of the array on the screen.

Resources