1 (edited by throgh 2021-04-14 22:59:56)

Topic: Learning C and guidance for guiding others?

Hello,

as a proposal for a possible own learning agenda:

1. The computer: A secret book?
1.1 The elementary parts of computing
1.2 Interfaces, but for what?
1.3 Communication is the key
1.4 And in the end: There is the platform ruling all

2. What about programming?
2.1 Recipes of the algorithm
2.2 Parts of programming-language (commands, variables and syntax)

3. So what about the C?
3.1 Introduction and basics
3.2 The syntax: Can be rude, but fair
3.3 Variables, someone's there for help?
3.4 Functions and procedures
3.5 How is that about data-structures? (Arrays and more)
3.6 What do you think about file-handles?
3.7 And now for something completely different: Keeping all together

Please note: There is not that much time to discuss this issue for long. But to keep all together I think it is better to start somewhere and this could be a possible structure. Done fast, of course! smile

Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

2 (edited by throgh 2021-04-14 23:17:06)

Re: Learning C and guidance for guiding others?

As an addition from my side: Please feel welcome to add also more chapters or subchapters. This proposal is a living document. You want another chapter with examples? Of course possible. You want more with correlation towards HyperbolaBSD and the algorithms? Of course. But keep in mind: Building a kernel is one big task and therefore the generic understatement: What is the machine and what is the platform? And there has to be furthermore an organization for development. Developers take different parts of a task, when bigger. Different tasks for a complete project! So this is not part of the guidacne for now. But stay curious as such a project needs attention. Big thank you towards the team for doing! It is up to us all: Community is also part developing. So you all can help!

Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

3

Re: Learning C and guidance for guiding others?

Example programs from the lesson today:

helloworld.c

#include <stdio.h>

int main() {
   // printf() displays the string inside quotation
   printf("Hello, World!\n");
   return 0;
}

randomnumber.c

#include<stdio.h>
#include<stdlib.h>
 
int main() 
{
      int count, num;
      printf("Ten Random Numbers:\t"); 
      for(count = 1; count <= 10; count++) 
      {
            num = rand() % 100;
            printf("%d\t", num);
      } 
      printf("\n");
      return 0;
}
Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

4 (edited by throgh 2021-04-16 00:04:26)

Re: Learning C and guidance for guiding others?

Here is the preview of the course-material and its layout:

https://files.catbox.moe/9218qd.png

Later I'd like to talk first about the major difference between programming with compilers with creating native binaries and the differences towards interpreter-languages. The major goal is to get everyone more prepared how to handle of course furthermore C as basic, but also the interest for creating packages for Hyperbola GNU/Linux-libre to support the development.

Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

5

Re: Learning C and guidance for guiding others?

Today another sample, this time enhanced: https://github.com/GeoB99/cli-calculator

Part for the learning-session is now:

1. Reading input-parameters into variables.
2. Doing further operations and calculations.
3. First Headerfiles in usage.

Following examples:

Integer Output

#include <stdio.h>

int main()
{
    int testInteger = 5;
    printf("Number = %d\n", testInteger);
    return 0;
}

Float and Double Output

#include <stdio.h>

int main()
{
    float number1 = 13.5;
    double number2 = 12.4;

    printf("number1 = %f\n", number1);
    printf("number2 = %lf\n", number2);
    return 0;
}

Printing Characters

#include <stdio.h>

int main()
{
    char chr = 'a';    
    printf("character = %c\n", chr);  
    return 0;
} 

Integer Input and Output

#include <stdio.h>

int main()
{
    int testInteger;
    printf("Enter an integer: ");
    scanf("%d", &testInteger);  
    printf("Number = %d\n",testInteger);
    return 0;
}

IMPORTANT NOTES: Regarding the more complex program above you can see, that there is no further license included. So that's also part of the lesson itself. It is impossible to make modifications or sharing them. So this is a playground to learn and analyze. But also: The code itself shows some problems. But you can experiment with it! smile

Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

6

Re: Learning C and guidance for guiding others?

Today two elementary points: The first one is the importance of speaking names for code and everything into. The generic example here is the comparison between the following:

int tmp; // temporary saved values, but for what purpose?
int varNumTemporarySavedCounter; // longer one, but speaking about purpose and usage within context

The point is: Using comments where you think they are useful. And using "speaking names" for all kind of code. When you get back to a project you've done within some days, months or even more, you have less to do for understanding what you've wanted to do back at a time. Readable code is thankful for everyone interested.

About data-structures: You want to save more complex data and do some operations with it? Well, think about arrays. Two examples, first for simple defined array:

Filename: array.c

#include<stdio.h>

int main()
{    
   int i=0; 
   int empID[5];
   empID[0]=10280;
   empID[1]=10260;   
   empID[2]=10270;   
   empID[3]=10285;    
   for(i=0;i<4;i++)
   {
       printf("%d\n",empID[i]);   
   }
   return 0; 
}

And another array, this time multiple dimensions, so called two-dimensional array following up.

Filename: array_2d.c

#include<stdio.h>

int main()
{
     int disp[2][3];
     int i, j;
     for(i=0; i<2; i++) 
     {
           for(j=0;j<3;j++) 
           {
                  printf("Enter value for disp[%d][%d]:", i, j);
                  scanf("%d", &disp[i][j]);
            }
     }
     printf("Two Dimensional array elements:\n");
     for(i=0; i<2; i++) 
     {
           for(j=0;j<3;j++) 
           {
                 printf("%d ", disp[i][j]);
                 if(j==2)
                 {
                       printf("\n");
                 }
           }
     }
     return 0;
}
Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

7

Re: Learning C and guidance for guiding others?

The point about pointers

Introduction

Until now all examples were done with variables, but for the upcoming next talks we need also something different and that is to talk and use pointers. So what's a pointer in comparison towards a variable? Reduced to one simple first definition: You don't save concrete values within a pointer, you save addresses within memory and point onto them as there is the content saved.

Before getting to the definition of pointers and more into the notation and arithmetic, it is better to understand what happens when we write the following code:

int digit = 42;

And that is leading towards the question: What exactly are pointers?

A block of memory is reserved by the compiler to hold the value for a variable. The name of this block is digit and the value stored in this block is 42. Now, to remember the block, it is assigned with an address or a location number.

The value of the location number is not important as it is a random value. But, it is possible to access this address using the ampersand or address of operator. The conclusion therefore: A variable has an address. A pointer can be assigned to this address, even changing it within the code! Just how to get the address of the variable defined above? Here is the example to get this more clear for the start:

#include <stdio.h>
int main() {
   int digit = 42;

   /* the memory-address where the variable digit is saved */
   printf("The memory-address of digit = %d.\n", &digit);

   /* getting the content itself again throughout pointer */
   printf("The value of digit = %d.\n", *(&digit));

   return 0;
}

How to define a pointer?

A pointer can be defined several ways:

int* pointer1;           /* can save an address, where a value with type Integer is saved */
int *pointer2;           /* you can use space before or after asterisk */
int * pointer3;          /* also possible as notation, depending on the code-style defined */
int *pointer4, *pointer5; /* definition of two pointers */
int *pointer6, number;    /* definition of one pointer and a variable with type Integer */

A defined pointer that has not yet been initialized shows a random address. When accessing this address, there may be a program crash or overwriting of the value stored at this address. Basic ruleset: Pointer should be initialized. When you want to check if a pointer is not initialized, you can use the keyword NULL within a comparison (look therefore at the paragraph Nullpointer). Followup examples for allocations and operators:

Allocation

int variable = 0;
int array[10];
int *pointer;
int *pointer2;
pointer = &variable;     /* with address-operator */
pointer = array;         /* with array, done without ampersand as not needed and handled internally from C */
pointer = pointer2;      /* with another pointer */
pointer = NULL;          /* with NULL (predefined keyword in syntax) */

Address-operator

int variable = 0; /* definition of a variable with type Integer, including initialization */
int *pointer = &variable; /* definition of a variable for a pointer with type Integer, including initialization */
printf("%p", (void*)&variable); /* output of the adress for the variable, depends on implementation for example this would result in hexadecimal output */

Content-operator

int variable = 3;
int *pointer = &variable; /* this is NOT the content-operator */
printf("%d", *&variable); /* output value "3" */
printf("%d", *pointer); /* output, value "3" */

* pointer = 5;
printf("%d", *pointer); /* output, value "5" */
* pointer = *pointer + 1;
printf("%d", *pointer); /* output, value "6" */

Nullpointer

If a pointer should not show up to no object, you can assign the value NULL. The pointer is invalid with it and can not be assigned until this is first done correctly, a dereference and usage of such pointer-definition usually leads to a runtime-error along with program abort. On the other hand the comparison of (data)object-pointers with NULL, which is also the main application for the macro (more about that later).

int *pointer;
pointer = NULL;

* pointer = 0;  /* error */

pointer = malloc( sizeof(*pointer) );
if ( pointer == NULL )
  puts("error while reserving memory");

NULL is a macro and is defined in multiple header-files (at least in STDDEF.h). The definition is specified by the standard implementation-dependent and implemented by the compiler manufacturer, for example:

#define NULL 0
#define NULL 0L
#define NULL (void *) 0

Pointer arithmetic

Using type char for example:

char character;
char *pointer = &character;
printf("%p\n", pointer);   /* output is for example the address 0019FF01 */
pointer = pointer + 1;
printf("%p\n", pointer);   /* output would be therefore 0019FF02 */

Another example, this time with Integer:

int number;
int *pointer = &number;
printf("%p\n", pointer); /* output would be some memory-address, for example 0019FF01 */
pointer = pointer + 2;
printf("%p\n", pointer); /* corresponding with the mentioned above: output would therefore here 0019FF09, meaning 0019FF01 plus 4 multiplied with 2 */

Addition and subtraction can be written as common as in C generally shortened here.

pointer += 5; /* pointer = pointer + 5 */
pointer++; /* pointer = pointer + 1 */

Always remember: A pointer is for the allocation and addressing of memory. All variable-types have therefore also a concrete, predefined size within memory to be reserved. So another example based upon that:

char *string = "hello";
char *pointer = &string;
char *pointer2 = pointer + 2;
ptrdiff_t difference;
difference = pointer2 - pointer;
printf("%d\n", difference);     /* result is here the difference in bytes, here "2" */

Management of dynamic memory

Dynamic memory in C as used for opposing automatic or static memory use in situations in which the required size is only known at runtime or the desired size exceeds the limits of automatic / static memory in the process. To request dynamic memory for the program during runtime the function malloc() is used in C (or the similar functions of calloc, realloc). The function reserves the required memory and returns a pointer to this. Likewise the release of this memory must be manually done with the function free() after use.

int *pointer = malloc(sizeof(int));  /* pointer at the start of a reserved memory-area at runtime, memory for one value of type Integer */

... usage of pointer ...
pointer[0] = 1;
printf("%d", pointer[0]);
* pointer = 2;
printf("%d", *pointer);

free(pointer);    /* get memory free */

... after free() the usage of the pointer will be no longer stable and foreseeable, undefined results incoming when doing that ...

Usage of pointer as function-parameter

void function(int *pointer) {
    *pointer = 1; /* the value for concurrent memory is overwritten with "1" */
}
int main() {
    int number = 0;
    function(&number); /* using variable as parameter */
    printf("%d\n", number); /* output will be "1" */
}

Conclusion

Pointers are there to help with especially dynamic constructions. But as much freedom C is giving here as much responsibility you have also: Not handling pointer-declarations correctly can result in far more big problems. Those are known in common as memoryleaks. You should check everytime: Is everything cleared at runtime correctly when you leave the point of development going forward towards development-tests?

Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

8

Re: Learning C and guidance for guiding others?

Files for lections:

Filename: pointer_char.c

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

int main() {
    char character;
    char *pointer = &character;
    printf("%p\n", pointer);   /* output is for example the address 0019FF01 */
    pointer = pointer + 1;
    printf("%p\n", pointer);   /* output would be therefore 0019FF02 */
}

Filename: pointer_error.c

#include <stdlib.h>
int main() {
   int *pointer;
   pointer = NULL;

   * pointer = 0;  /* error */

   pointer = malloc( sizeof(*pointer) );
}

Filename: pointer_function.c

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

void function(int *pointer) {
    *pointer = 1; /* the value for concurrent memory is overwritten with "1" */
}
int main() {
    int number = 0;
    function(&number); /* using variable as parameter */
    printf("%d\n", number); /* output will be "1" */
}
Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

9

Re: Learning C and guidance for guiding others?

What is a stack

(Quote from Wikipedia)

In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations:

  • Push, which adds an element to the collection, and

  • Pop, which removes the most recently added element that was not yet removed.

Coming here an example for a stack:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
struct Stack {
     int top;
     unsigned capacity;
     int* array;
};
struct Stack* createStack(unsigned capacity)
{
     struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
     stack->capacity = capacity;
     stack->top = -1;
     stack->array = (int*)malloc(stack->capacity * sizeof(int));
     return stack;
}
int isFull(struct Stack* stack)
{
     return stack->top == stack->capacity - 1;
}
int isEmpty(struct Stack* stack)
{
     return stack->top == -1;
}
void push(struct Stack* stack, int item)
{
     if (isFull(stack))
     return;
     stack->array[++stack->top] = item;
     printf("%d pushed to stack\n", item);
}
int pop(struct Stack* stack)
{
      if (isEmpty(stack))
      return INT_MIN;
      return stack->array[stack->top--];
}
int main()
{
      struct Stack* stack = createStack(100);
      push(stack, 11);
      push(stack, 12);
      push(stack, 33);
      printf("%d popped from stack\n", pop(stack));
      printf("%d popped from stack\n", pop(stack));
      printf("%d popped from stack\n", pop(stack));
      return 0;
}

With comments and better formatting:

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

/*
    definining struct
*/
struct Stack {
     int top;
     unsigned capacity;
     int* array;
};

/*
    function "createStack"
    parameter:
              unsigned numeric capacity - absolute maximum of possible entries within stack

    This functions is creating the initial data-structure with holding a maximum of entries (capacity).
    Returns the structure as pointer towards the predefined datatype.
*/
struct Stack* createStack(unsigned capacity)
{
     struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
     stack->capacity = capacity;
     stack->top = -1;
     stack->array = (int*)malloc(stack->capacity * sizeof(int));
     return stack;
}

/*
    function "isFull"
    parameter:
              pointer for datatype stack

    This function is checking if the defined stack is full.
*/
int isFull(struct Stack* stack)
{
     return stack->top == stack->capacity - 1;
}

/*
    function "isEmpty"
    parameter:
              pointer for datatype stack

    This function is checking if the defined stack is just empty. 
*/
int isEmpty(struct Stack* stack)
{
     return stack->top == -1;
}

/*
    function "push"
    parameter:
              pointer for datatype stack
              item to be pushed into the stack as numeric

    This function pushes a new element / item within the stack on top.
*/
void push(struct Stack* stack, int item)
{
     if (isFull(stack)) return;
     stack->array[++stack->top] = item;
     printf("%d pushed to stack\n", item);
}

/*
    function "pop"
    parameter:
              pointer for datatype stack

    This function removes the last element to be find on top of the data-structure.
*/
int pop(struct Stack* stack)
{
      if (isEmpty(stack)) return INT_MIN;
      return stack->array[stack->top--];
}

int main()
{
      // defining a new pointer with given datatype and create this with possible 100 entries
      struct Stack* stack = createStack(100);

      // adding new elements
      push(stack, 11);
      push(stack, 12);
      push(stack, 33);

      // removing elements, last one added as first to be removed
      printf("%d popped from stack\n", pop(stack));
      printf("%d popped from stack\n", pop(stack));
      printf("%d popped from stack\n", pop(stack));
      return 0;
}
Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!

10

Re: Learning C and guidance for guiding others?

The keyword "void"

The keyword void (especially not as pointer) means "nothing" in C.

But what about the pointer void*? This means "pointer to anything" in languages that support raw pointers (C and C++). This is an unfortunate decision because it does make void mean two different things. This is one special reference being added here at this point at this type and definition was not clear defined before.

There is a difference between

void myFunction(...)
{

}

and the usage of void for being a pointer like

void * pointer;

Food for thoughts and experiments:

#include <stdio.h>

void f ( int i )
{
    if ( i < 4 )
    {
        void * v = &i;
        printf( "%d, %p\n", i, v ); 
        f( i + 1 );
        printf( "%d, %p\n", i, v );
    }
}

int main( void )
{
    f( 0 );
}

Here you can also see, that especially the function printf gets another possible notation to give out pointer-address with with the keyword %p. But for the time now: Try the example out! smile

And here the example with comments included:

#include <stdio.h> // including generic header from stdlib

/*
    definition of function f, only accepting one parameter i type Integer
*/
void f ( int i )
{
    // input-parameter should only have the maximum 4 at this point
    if ( i < 4 )
    {
        void * v = &i; // point towards content of input-parameter, reasoning to get the exact hex-value for the address
        printf( "%d, %p\n", i, v );  // output for input-parameter and pointer
        f( i + 1 ); // calling the function again, incrementing input-parameter step-wise
        printf( "%d, %p\n", i, v ); // again output for input-parameter and pointer
    }
}

int main( void )
{
    f( 0 ); // calling function with starting "0"
}
Human being in favor with clear principles and so also for freedom in soft- and hardware!

Certainly anyone who has the power to make you believe absurdities has the power to make you commit injustices: For a life of every being full with peace and kindness, including diversity and freedom. Capitalism is destroying our minds, the planet itself and the universe in the end!