Skip to content

Latest commit

 

History

History
897 lines (640 loc) · 34.6 KB

readme.md

File metadata and controls

897 lines (640 loc) · 34.6 KB


"The world, even the smallest parts of it, is filled with things you don't know."


Summary


1337



There are no teachers but a pedagogic team that ensure that students do not harm the material and provide a cursus syllabus to follow. What is learned is hence mainly achieved through peer-to-peer project review and RTFM.


3 Mandatory tips to succeed in 1337 :

1 - WORK AND DUNNOT LET THE BLACK HOLE ABSORB YOU.

2 - WORK MORE, I MEAN YOU HAVE TO WORK EVEN MOAR!

3 - RTFM.


Libft


☕ Artistic view of your LIBFT :



Subject :


📖 ENGLISH PDF


ℹ️ What exactly is LIBFT ?



This project aims to code a C library regrouping usual functions that you’ll be allowed to use in all your other projects.


~ Coding simple C programs / General knowledge with examples :

시작이 반이다The beginning is half of the way (Korean proverb)

First by installing a C compiler on your computer

  • On Windows it is a bit tricky, you will have to install Mingw
  • On Linux it is pretty straightforward since it is only installed and if not apt-get will make it easy.
  • On MAC it is not much more difficult, i will mention it bellow.

Structure of a code in C

  • C code is written in a file with the extension .c . It can be modified with any text editor ( emacs , vim , etc).
  • C code is executed by following line-by-line instructions in functions .
  • A function consists of several parts:

Declaration of the variables used

Instructions

Value returned at the end of the function (optional)

The first function called is the main function . There must always be one in a C program.

A function is declared as follows:

	type_of_returned_variable 	function_name ( type_argument1 name_argument1 , type_argument2 name_argument2 )  
	{
		statement1;
		statement2;
		statement1;
		statement2;
		return (return_value);
	}
  • A function can call other functions in one statement:
		return_value = my_function(argument1, argument2);
  • The "return" statement returns a value and stops the execution of the function. If we put instructions after a return, they will never be executed.
  • A function must be declared before it is called. So the main must be at the very bottom of the file.

C Data Types

Instructions use variables. These variables have types allowing to define their size (in bytes). In a variable, we can only store a number, whose lower and upper limit depends on the type.

  • I will only list the main ones :
Data Type Bytes Description
char 1 Used for text
bool 1 Used to return true or false, you will need the header <stdbool.h>
short 2 Half the size of an integer, used to optimize memory
int 4 Loop Counter, operations on integers
long 8 Twice the size of an integer, used when overflow is a problem
float 4 Used for computer graphics
double 8 Used for computer graphics, more precised than float but takes more memory
unsigned . Apply to char, short, int and long, means than it cannot have negative values

(This table is not necessarily correct, it depends on the architecture of your machine. It is, for example, not valid in 64 bits.)

  • char, short, int, long and their respective unsigned can only contain integers (2, 6, 42, 254, ...).

  • float, double and long double can contain floating point numbers (2.0, 6.21, 42.5694, -3.457, ...).

  • The keyword void signifies the absence of a variable, for example, if a function returns nothing or if it does not take a parameter.

  • There are pre-defined types that have a name allowing you to know their roles. For example, size_t contains the size of an array (see what an array is later.) ssize_t will be used to iterate over an array.

  • To use a variable, you must declare it by giving it a name:

	type 		name ;
  • In a function, we declare all the variables before using them. Function names should contain only lowercase letters, numbers, and underscores ("_"). They must be in English and self- explanatory . Thanks to the name of the variable, we must understand what it contains, what it is used for in the program. The variable name i is often used for a counter.
  • Variables are internal to functions. A variable declared in a function does not exist anywhere else than in this one.
  • It is possible to declare so-called global variables by declaring them outside of any function. It is not recommended, it is better to avoid them as much as possible.

An example...

... is better than a long speech!

	int subtraction ( int  a , int  b )
	{
		int 	result;

		result = a - b;
		return (result);
	}

	int main ( void )
	{
		int	i;

		i = 3;
		i = i + 5;
		i = subtraction(i, 2);
		return (0);
	}

Here's what's going on here :

  • The program begins its execution with the main function (it takes no parameters).
  • In it, we declare a variable of type int and name " i ".
  • We then assign a value to the variable i using the " = ". --> i = 3.
  • The next statement takes the value of i (3) and adds 5 to it. It then puts that result into i, which overwrites its old value. --> i = 8.
  • The following statement calls a function to which it gives two arguments: i (8) and 2.
  • We then enter the subtraction function. We see that it takes 2 arguments of int type (a and b) as parameters. That's good, that's what we sent him during the call! --> a = 8 and b = 2.
  • We then declare a new variable of type int named "result". --> a = 8, b = 2 and result = unknown value (/!\ not necessarily = 0)
  • We perform the calculation of a - b, ie 8 - 2, and we put this value in "result". --> a = 8, b = 2 and result = 6
  • The return statement returns the value of result and we return to the main function.
  • The value that the function returned is placed in i. --> i = 6. (a, b and result no longer exist: they were specific to the subtraction function).
  • The main function has then completed its instructions and is therefore the last instruction that returns a value.
  • The value 0 means that the execution of the program went well. Another value means there was an error.
  • Now, to test this program, we will compile it and launch it. We will realize that it does not display anything.

You should then try to recode basic C functions


Pointers

In computer science, a pointer is a programming language object that stores a memory address.

Pointer is a fundamental concept of C programming.

You can think of your computer's memory as a contiguous array of bytes. Each time that you make an innocent declaration and assignation such as int a = 5, this value is written into your computer's memory on 4 bytes (integer size). This value will be written at a specific memory address, the stack (fast access to memory) if no memory allocation, else it will be stored deeper in the heap. This address also has a value!

Example illustrating the difference a pointer - a memory address pointing to value - and a value:

#include <stdio.h>

int main(void)
{
	int a = 5;	// declaring an integer variable and assigning the value of 5
	int *ptr;	// declaring a pointer to integer
	int b;		// declaring an integer variable
	printf("ptr's value: %2d, ptr's address: %p\n\n", *ptr, ptr);

	ptr = &a;	// pointer ptr points to what is stored at the memory address of variable a
	b = a;		// b will take the value and not the address
	a = 42;		// b is still equal to 5, but ptr will return 42, which is the value now stored at a's location;
	printf("  a's value: %2d,   a's address: %p\n", a, &a);
	printf("ptr's value: %2d, ptr's address: %p\n", *ptr, ptr); // you will get the same as above, notice that you have to dereference the pointer with * to get the value, and using the pointer alone (ptr) will give you the memory address.
	printf("  b's value: %2d,   b's address: %p\n", b, &b);
	//printf("Size of ptr: %zu\n", sizeof(ptr)); // size of ptr in bytes, 8 on my system.
	return (0);
}

You will get this kind of output:

ptr's value:  1, ptr's address: 0x7ffd99493000

	a's value: 42,   a's address: 0x7ffd99492f08
	ptr's value: 42, ptr's address: 0x7ffd99492f08  <-- they now match thanks to ptr = &a
	b's value:  5,   b's address: 0x7ffd99492f0c

NB: On the second printf you will get the value that you got for a, notice that you have to dereference the pointer with * to get the value, and using the pointer alone (ptr) will give you the memory address.

See this example with int a = 9:


⏫ Back To Top


The compilation

We compile with gcc (aka cc ).

The compiler then generates an (executable) a.out file . It is possible to change the name of the file using the -o option

     gcc -o executable_name my_code.c

If there are one or more errors, they will be displayed and the compilation will stop. However, some "errors" may not prevent compilation, they are called Warnings . It is nevertheless very important to correct these small errors because most of the time, they will disturb the normal operation of the program.

To display more Warnings, it is possible (and recommended) to add options (called compilation flags):

  • -w : Disable all warnings (not recommended)
  • -Wextra : Displays even more warnings
  • -Wall : Display more warnings
  • -Werror : Consider warnings as errors and stop compiling
  • -ansi : Displays warnings in case of non-compliance with the ISO C90 standard Many more are available. Refer to the gcc man . It is also possible to ask the compiler to perform (or not) optimizations:

-O0 : Disables all optimizations

-O1 : Level 1 optimization

-O2 : Level 2 optimization

-O3 : Level 3 optimization However, I don't recommend using these while building a C program. (Once it's over, why not)

You can compile several C files for the same program.

Compilation example:

     gcc -O0 -Wall -Wextra -Werror -ansi -o my_executable my_code.c

To avoid having to type this long command each time you compile, make yourself an alias! Once the program is compiled, you can run it to see what it does:

     ./my_executable

Values are stored differently depending on the kind of system you are using.

Little endian means that the value is stored in memory from left to right, big endian means it is stored from right to left.

See this example with int a = 9:


little endian :

   higher memory
      ----->
+----+----+----+----+
|0x09|0x00|0x00|0x00|
+----+----+----+----+
|

&x = 0xff

big endian:

    +----+----+----+----+
    |0x00|0x00|0x00|0x09|
    +----+----+----+----+
    |
   &x

To find out if your system is big or little endian you can use the following function:

int x = 9;

if (*(char *)&x == 0x09) // we cast x as a byte to get its very first byte, it will return true (meaning little endian) if the first byte is equal to 9.

⏫ Back To Top


ft_putchar

A minimalist c program that will puzzle beginners, write it in a file named a.c and create a.out with gcc a.c && ./a.out

The following program will print a char by making use of write

#include <unistd.h>

void	ft_putchar(char c) // void because the function does not return any value, it writes directly, char is the type of the variable c that is given as parameter to the function ft_putchar by the main function.
{
	write(1, &c, 1);			// ssize_t write(int fd, const void *buf, size_t count); or in human language: write count letters of buf (which is a pointer) to fd (if fd = 1 this is your terminal, stdout)
}

int	main(void)
{
	ft_putchar(42);				// will print a star
	// ft_putchar(42 + '0');	// will only print 4
	// ft_putchar("4");			// will not work, you are using " instead of ', so C language think it is a char array.
	return 0;
}

Once you understand well how to print a character, you should try to return the length of many together (it is called a string)

ft_strlen

#include <unistd.h>

int		ft_strlen(char *str)
{
	int i = 0;					// set variable i to 0
	while (str[i] != '\0')		// while the char array does not reach a NULL character
		i++;					// increment i, equivalent of i = i + 1;

	return i;					// return i variable to the caller function
}

int main(void) {
	int i = ft_strlen("1337 is the answer");	// declare i, call the function ft_strlen, and assign its output to i
	printf("%d", i); // remember that it is forbidden to submit a function with printf during the Piscine
	return 0;
}

NB: remember that it is forbidden to submit a function with printf during the Piscine

ft_putstr

Then print a whole string by recoding the libc function 'puts':

#include <stdio.h> // header for puts

int main(void)
{
	puts("1337 is the answer");
	return 0;
}

This can be achieve by using and index that starts on the first character and is progressively incremented until NULL as string are NULL terminated:

#include <unistd.h>

void	ft_putstr(char *str) {
	int i = 0;

	while(str[i] != '\0')
		write(1, &str[i++], 1);
}

Along with the main function slightly modified to make use of your code:

int main(void) {
	ft_putstr("You are the answer\n");
	return 0;
}

You can also use only the pointer since you do not care of the return value (the function type being void)

#include <unistd.h>

void	ft_putstr(char *str)
{
	while(*str)
		write(1, s++, 1);
}

Or even use the length of the string to print the whole string at once, hence avoiding many system calls (write) that are costly for the program execution:

void	ft_putstr(char *str)
{
	write(1, str, ft_strlen(str));
}

NB: You have to include ft_strlen in the same file AND above the function to make it work.

Next you should study the different concepts in programming, especially spend time understanding the different C data types, the concept of pointers and arrays, because it is what you have been using up to now and it will only get more complicated.


Coding

⏫ Back To Top

Some quotes :

“Everybody should learn to program a computer, because it teaches you how to think.” - Steve Jobs, former CEO and creator of Apple

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

First, solve the problem. Then, write the code.” – John Johnson

“Coding, it's an endless process of trial and error, of trying to get the right command in the right place, with sometimes just a semicolon making the difference between success and failure. Code breaks and then it falls apart, and it often takes many, many tries until that magical moment when what you're trying to build comes to life.” - Reshma Saujani, Entrepreneur, founder of Girls Who Code

“Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday’s code.” – Dan Salomon

“Fix the cause, not the symptom.” – Steve Maguire

“Simplicity is the soul of efficiency.” – Austin Freeman


Miscellaneous :


In computer engineering, computer architecture is a set of rules and methods that describe the functionality, organization, and implementation of computer systems. The architecture of a system refers to its structure in terms of separately specified components of that system and their interrelationships. Some definitions of architecture define it as describing the capabilities and programming model of a computer but not a particular implementation. In other definitions computer architecture involves instruction set architecture design, microarchitecture design, logic design, and implementation.


If an individual wants to grow and solve projects for a team then they should be proficient in algorithms. As a developer, your everyday work is to solve problems and algorithms solve problems very efficiently. Practicing algorithms will increase you skill and your visibility at work.


Complexity of an algorithm is a measure of the amount of time and/or space required by an algorithm for an input of a given size (n).


⏫ Back To Top


⏫ Back To Top

“Unlike most computer languages, C allows the programmer to write directly to memory. Key constructs in C such as structs, pointers and arrays are designed to structure, and manipulate memory in an efficient, machine-independent fashion.”


The assembly language isn’t like other higher-level programming languages such as Java, Python, C#, etc. The language syntax is symbolically much close to machine code as you’re working directly with memory locations and addresses inside the processor.




⏫ Back To Top






WebDev

⏫ Back To Top

Web development gives you the opportunity to express yourself creatively on the internet. ... Fortunately, the high demand, easy-to-learn, fun-to-experience life of a web developer is always a great choice for someone ready to have an exciting career in code.



Robotics

⏫ Back To Top

Robotics is an interdisciplinary branch of computer science and engineering. Robotics involves design, construction, operation, and use of robots. The goal of robotics is to design machines that can help and assist humans. Robotics integrates fields of mechanical engineering, electrical engineering, information engineering, mechatronics, electronics, bioengineering, computer engineering, control engineering, software engineering, mathematics, etc.



Security

⏫ Back To Top



Markdown

⏫ Back To Top


Markdown Articles Tool is a free command line utility designed to help you manage online Markdown documents (e.g., articles). You can download text with images using deduplication and convert to the different formats. The Markdown Articles Tool is available for macOS, Windows, and Linux. It’s written in Python — if you want to use separate functions, you can just import the package.


:octocat: Git/Github

⏫ Back To Top



Linux

⏫ Back To Top



News and Articles

⏫ Back To Top



Useful Github Repos

⏫ Back To Top



Books


Book Impression Author(s)
Introduction to Algorithms ⭐⭐⭐⭐⭐ Thomas H. Cormen, Charles E. Leiserson, Ronald Rivest, Clifford Stein
21st Century C ⭐⭐⭐ Ben Klemens
Computer Science Bottom to Up ⭐⭐⭐⭐⭐ Ian Wienand
The Linux programming interface a Linux and UNIX system programming handbook ⭐⭐⭐⭐ Michael Kerrisk
Write Great Code, Volume 2 Thinking Low-Level, Writing High-Level ⭐⭐⭐⭐ Randall Hyde

Fun Stuff

⏫ Back To Top