C: Assignments Day 2

Today we have several problems for you to tackle. Parts should look and feel familiar from Day 1, though we will add more features as we go. Those problems are modeled after exercises in Python and, thus, allow you to learn how data structures compare when transitioning from python to C (and later C++).

Problem 1: Reviewing the stress transformation problem

Navigate to /code/c/ExerciseDay2/ex2-1/ to find another solution for the stress transformation problem. The main difference to Frank’s solution is that this one places functions in separate files, as well as adds a header file that contains the definition of the function without its implementation.

Compiling this version requires multiple steps:

gcc stresstransform.c -c
gcc exercise2-1.c stresstransform.o -lm

And you can run the executable as


Imagine doing this for many more files, usually tens to hundreds. That would be painstaking and inefficient and very error prone. Software engineers developed several tools to simplify and automate the compile process. One of those tools is cmake, a member of the make family of tools. You find a configuration file names CMakeList.txt in the source folder. The configuration file is a plain text file, so you can and should check out how it is written.

The compile process now becomes

1. a configuration step - done only once or every time you are adding a file to the project. Inside the source folder, execute

$ mkdir build
$ cd build
$ cmake ..

This will check your system for compilers and other development tool and create a Makefile in each source folder.


Placing the compile files into a build folder makes cleanup easier: simply delete the entire build folder when done. It can be regenerated easily using the above procedure.

2. From now on, every time you make changes to any of the files within your project, simply type

$ make

to recompile all portions necessary and link all parts to one executable. That process remains exactly the same regardless of the number of files in your project. Give it a try and see how convenient this is especially for projects provided by somebody else.

Problem 2: Using structures

The implementation of StressTransform() was intentionally done a bit clumsy, just the way a beginner might write it. Your task in this exercise is to create a structure

typedef struct {
        double sigx;
        double sigy;
        double tau;

and modify the code from the previous exercise to utilize the much easier to read data structure provided by this struct. Use the code skeleton provided in /code/c/ExerciseDay2/ex2-2 to develop that code. The included CMakeList.txt shall be used to compile your code.


Your modified StressTransform(...) will require a pointer to a STRESS type object. The way to achieve that in an efficient manner is to use a typedef struct {...} STRESS ;.

In addition, inside the function that receives the pointer to a structure, assigning a new value to entries in such a structure requires the syntax

void StressTransform(STRESS stressIn, STRESS *stressOut, ....) {
  stressIn->sigx = ... ;

This replaces the form

*sigx = ... ;

used for scalar-valued arguments.

Problem 3: Writing data for use by other programs: CSV

While C is very powerful for numeric computations, it can be impractical to generate graphs or fancy images using the computed values. A more efficient way is to use C to do the analysis, write results to an easily readable file, and use specialized tools for the post-processing. One common and simple format is CSV (comma-separated-values), which van be read easily by MATLAB, python, or Excel.

Your task: modify the code given in /code/c/ExerciseDay2/ex2-3 to

1. Take one argument \(\Delta\theta\) in degrees after the name of the executable, defining the increment at which transformed stress values shall be written:

$ Exercise2-3 5.0

The format of the output shall be for one angle per line, organized as follows:

theta, sigma_x, sigma_y, tau_xy

Output shall commence until an angle of \(180^\circ\) has been reached or exceeded.

Once your code outputs the information, run it once more and save the results to a file names list.csv (make sure to add the spaces around the ‘>’)

$ Exercise2-3 5.0 > list.csv


You may want to download the file list.csv to your local computer before trying the next step, for it will require access to your display. That file can be opened in Excel and plotted there. A more efficient way is to prepare some nice plotting code, such as the provided plotter.py. In the same folder where you placed list.csv run

Windows 10

>> python.exe plotter.py

MacOS or Linux

$ python3 plotter.py

Isn’t that nice?

Problem 4: Writing to a binary file

Modify the code generated in the previous exercise to write a binary file names mohrcircle.dta instead of the formatted ASCII data. The data shall be exported in clocks composed of double theta followed by a block of STRESS (or the three components of stress as double).

You may be working of your code or use the provided code skeleton in /code/c/ExerciseDay2/ex2-4.

This time, your code should be totally silent on execution. The only sign of success will be the creation of the data file. For the next steps, run your program with the following parameters:

$ Exercise2-4 5.0


How large do you expect the binary file to be? Discuss, predicts, and check using

$ ls -l mohrcircle.dta

You should be able to predict the exact number (to the byte!).


This problem comes with validation code, something worth developing every time you are working on software that will be modified over an extended period of time and/or by multiple people.

The validation consists of (1) a C code parse.c which reads the binary file and outputs its contents to a CSV file, and (2) a shell script validate.sh that attempts to run the validation code and compares the output generated from your binary file to an output generated by a correct code.

Run the validation script as

$ sh ./validate.sh

and check its feedback. (That script may not run on all platforms.)


Binary files are not readable by traditional ASCII editors (text editors). Doings so, usually shows some unintelligible scramble of characters, sometimes leaving your terminal in an unusable state.

However, you may view binary files using a hex-dump utility. That approach may help you understand and recover the structure of a binary file (though it still requires some practice and skill and luck). You may try such a tool on your binary file using

$ xxd mohrcircle.dta | less

where the | less pipes the output in a pager utility that allows you to search the output, jump pages forward and backward, or move to any specific line. Press q to exit this utility.

Problem 5: Reading From a binary file and Memory Allocation

Reading of data from files and placing them into containers such as Vectors is easy if you know the size of the data you are reading. If this is unknown the problem becomes more tricky. The solution presented on slide 22 worked for a small number of inputs, but failed with a segmentation fault for larger problems. You are to fix the problem. A copy of the offending file file3.c has been placed in the directory ex2-5 along with two files. The program can handle the first small.txt, it will fail with the second big.txt. Can you make the program work. The solution will test your understanding of file I/O, memory management and pointers.

The file3.c is as shown below. You need to put some code to replace comment at the line 41.

 3 * program to read values from a file, 
 4 * with each line being csv list of int and two double
 5 *
 6 * program fails if num lines > 100
 7 *    Major flaw will cause data to be overwritten outside array 
 8 *    bounds if #lines > 100 & will ultimataly lead to a segmentation fault
 9 *
10 * Exerise is to fix flaw WITHOUT just setting maxVectorSize incredibly large
11 *
12 * written: fmk
13 ******************************************************************* */
15#include <stdio.h>
16#include <stdlib.h>
18int main(int argc, char **argv) {
20  if (argc != 2) {
21    fprintf(stdout, "ERROR correct usage appName inputFile\n");
22    return -1;
23  }
25  FILE *filePtr = fopen(argv[1],"r"); 
27  int i = 0;
28  float float1, float2;
29  int maxVectorSize = 100;
30  double *vector1 = (double *)malloc(maxVectorSize*sizeof(double));
31  double *vector2 = (double *)malloc(maxVectorSize*sizeof(double));  
32  int vectorSize = 0;
34  while (fscanf(filePtr,"%d, %f, %f\n", &i, &float1, &float2) != EOF) {
35    vector1[vectorSize] = float1;
36    vector2[vectorSize] = float2;
37    printf("%d, %f, %f\n",i, vector2[i], vector1[i]);
38    vectorSize++;
40    if (vectorSize == maxVectorSize) {
41      /* some code needed here .. programming exercise */
42    }
43  }
45  fclose(filePtr);  

The small.txt file is as shown below.

 10, 0.153779, 0.560532
 21, 0.865013, 0.276724
 32, 0.895919, 0.704462
 43, 0.886472, 0.929641
 54, 0.469290, 0.350208
 65, 0.941637, 0.096535
 76, 0.457211, 0.346164
 87, 0.970019, 0.114938
 98, 0.769819, 0.341565
109, 0.684224, 0.748597


No cmake or Makefile has been provided. You can compile the file with icc or whatever compiler you are using. The program takes a single input, the file to read. To compile and test the program, issue the following at the terminal prompt.

icc file3.c -o file3
./file2 small.txt
./file2 big.txt