C development

Inroduction

C language development.


C17: Informal name for ISO/IEC 9899:2018 (latest as of 2022-november)

C11: Informal name for ISO/IEC 9899:2011, replaced by C17

C99: Informal name for ISO/IEC 9899:1999, replaced by C11 (supported by IDE Dev C++)

C90: Informal name for ISO/IEC 9899:1990 , replaced by C99

Tools

CodeBlocks

Linus, Mac and Windows, last release from 2020 (as of 2022).

https://www.codeblocks.org/

Configuration of the C lang spec :

Settings > Compiler... > Compiler Flags

Have g++ follow the C++ 17 ISO C++ language standard [-std=c++17]


Dev C++

Windows only, last release from 2015 (as of 2022).

https://sourceforge.net/projects/orwelldevcpp/

Configuration of the C lang spec (so that for inline variables are allowed):

Tools > Compiler Options... > Settings > Code Generation

Language standard (-std): ISO C99


Visual Studio Code

Installing the IDE commended extensions for C (suggested when opening a .c file): C/C++ Extension Pack


CLion

https://www.jetbrains.com/clion/

JetBrains cross-platform IDE for C and C++.

Commercial tool w/ 30-day trial. Allows refactoring, etc.


Include directives

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

#include <string.h>

#include <math.h>



Macro directives

Note: Macros don't have a semicolon (;) at the end.

#define PI 3.1416

Data types

Basic

int a = 1; //2 bytes from -32768 to 32767

unsigned int f = 123; //4 bytes on most data models

char b = 'z'; //1 byte from 0 to 255 (for a character use 'unsigned int')

float c = 1.5456456; //4 bytes

bool //Include stdbool.h

double d = 15555555.55555555; //8 bytes

short v = 2; //2 bytes from -128 to 127

long e = 12; //4 bytes

long double r = 12.33323;

Array

Syntax: DataType arrayName[size] = {value1, value2, value3, ..., valueN}

DataType arrayName[rowSize][columnSize];

DataType arrayName[blockSize][rowSize][columnSize]; //blockSize=total number of 2D arrays

Arrays are automatically passed by reference, w/out '&', see section "Sample: Arrays always passed by reference".

char name[40]; //Array of 40 chars

int aname[3] = {2, 7, 27};

char name[1920][1080]; //1920 rows x 1080 columns

int aname[2][3] = {{1,2,3}, {4,5,6}}; // 2 rows x 3 columns, initialized

int aname[2][3] = {1,2,3, 4,5,6}; // 2 rows x 3 columns, initialized alternative

int min[1][1][1] = {{{100}}}; //3D array of 1 element

// 'arr' is a 3D array w/ 2 groups, each containing 3 groups of 4 numbers:

int arr[2][3][4] = { { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} },

{ {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} } }; //2 3x4 2D arrays


Struct

Declaring a new type 'Asignatura' w/ an struct:

typedef struct Asignatura{

char Materia[30];

}Asignatura;


typedef struct Alumno{

Asignatura Asignaturas[5];

}Alumno;


int main(){

Alumno Jorge, Juan;


strcpy(Jorge.Asignaturas[0].Materia, "Matematicas");

return 0;

}

Declaring an array w/ 5 structs:

struct persona{

char nombre[20];

int edad;

}personas[5];

Generic sample:

struct persona{

char nombre[20];

int edad;

}

persona1 = {"Jorge",19},

persona2 = {"Ricardo",18};



int main() {


printf("\nSu nombre es: %s",persona1.nombre);

printf("\nLa edad es: %i\n\n",persona1.edad);


printf("\nSu nombre es: %s",persona2.nombre);

printf("\nLa edad es: %i",persona2.edad);



return 0;

}

Nested struct sample:

#include <stdio.h>


struct infoDireccion{

char direccion[30];

char ciudad[20];

char provincia[20];

};

struct empleado{

char nombre[30];

struct infoDireccion dirEmpleado;

double salario;

}empleados[2];


int main() {


for (int i = 0; i < 2; i++){


fflush(stdin);


printf("%i) Escribe su Nombre: ",i+1);

gets(empleados[i].nombre);

printf("%i) Escribe su Direccion: ",i+1);

gets(empleados[i].dirEmpleado.direccion);

printf("%i) Escribe el nombre de tu Ciudad: ",i+1);

gets(empleados[i].dirEmpleado.ciudad);

printf("%i) Escribe tu Provincia: ",i+1);

gets(empleados[i].dirEmpleado.provincia);

printf("%i) Escribe tu Salario: ",i+1);

scanf("%lf",&empleados[i].salario);

printf("\n");

}


for (int i = 0; i < 2; i++){

printf("\n\nDatos del empleado numero %i: ",i+1);

printf("\nNombre %s ",empleados[i].nombre);

printf("\nDireccion: %s ",empleados[i].dirEmpleado.direccion);

printf("\nCiudad: %s ",empleados[i].dirEmpleado.ciudad);

printf("\nProvincia: %s ",empleados[i].dirEmpleado.provincia);

printf("\nSalario: %.2lf",empleados[i].salario);

printf("\n");

}

return 0;

}


Typedef

The keyword typedef can be used to give a type a new name.

typedef unsigned char BYTE;

Then, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:

BYTE b1, b2;

Example w/ an struct:

typedef struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

} Book;

And a variable of type Book can be declared:
Book book;

Example of pointer to struct:

Note that an arrow is used when accessing a pointer.

struct Alumno Alumno1; //Creating a pupil

struct Alumno *apAlumno;

apAlumno = &Alumno1;

strcpy(apAlumno->direccion.cCalle, "Tepito");

apAlumno->direccion.CP = 54321;



Functions: math.h

acos(x)

Calcula el arcocoseno de x


asin(x)

Calcula el arcoseno de x


atan(x)

Calcula el arcotangente de x


ceil(x)

Redondea al entero mayor más cercano


cos(x)

Calcula el coseno de x


fabs(x)

Devuelve el valor absoluto de x


floor(x)

Redondea al entero menor más cercano


fmod(x, y)

Calcula el resto de la división de x/y


pow(x, y)

Calcula x elevado a la potencia y

area = pow(lado, 2);


sin(x)

Calcula el seno de x


sqrt(x)

int numero = 16;

squareRoot = sqrt(numero);


tan(x)

Calcula la tangente de x

Functions: stdio.h

https://www.tutorialspoint.com/c_standard_library/stdio_h.htm


int fclose(FILE *stream)

Closes the stream. All buffers are flushed.

See fopen for an example.


int feof(FILE *stream)

Tests the end-of-file indicator for the given stream.

Param stream Pointer to a FILE object that identifies the stream.

Returns a non-zero value when End-of-File indicator associated with the stream is set, else zero is returned.


int ferror(FILE *stream)

Tests the error indicator for the given stream.

Param stream Pointer to a FILE object that identifies the stream.

Return If the error indicator associated with the stream was set, the function returns a non-zero value else, it returns a zero value.


int fflush(FILE *_File)

fflush(stdin); //Free input buffer, eg, after several gets or scanf executions


int fgetc(FILE *stream)

Param stream Pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return The character read as an unsigned char cast to an int or EOF on end of file or error.


char *fgets(char *str, int n, FILE *stream)

char nombre[20];

fgets(nombre, 20, stdin);


FILE *fopen(const char *filename, const char *mode)

https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm

Param mode:

r Opens a file for reading. The file must exist.

rb Binary. Para lectura.

rt Open a text file for reading. The file must exist.

r+ Opens a file to update both reading and writing. The file must exist.

r+b [or rb+]Binary. Para actualización (lectura y escritura)

r+t [or rt+]Open a text file for both reading and writing. The file must exist.


w Creates an empty file for writing. If a file w/ the same name exists,

its content is erased and the file is considered as a new empty file.

wb Crea un archivo binario para escritura.

wt Open a text file for writing.

If the file already exists, its contents are destroyed.

w+ Creates an empty file for both reading and writing.

w+b [or wb+]Crea un archivo binario para lectura / escritura.

w+t [or wt+]Open a text file for both reading and writing.

If the file already exists, its contents are destroyed.


a Appends to a file. Writing operations, append data at the end of the file.

The file is created if it does not exist.

ab Open a binary file in append mode for writing at the end of the file.

fopen() creates the file if it does not exist.

at Open a text file in append mode for writing at the end of the file.

fopen() creates the file if it does not exist.

a+ Opens a file for reading and appending.

a+b [or ab+]Añade o crea un archivo binario para lectura / escritura.

a+t [or at+]Open a text file in append mode for reading or updating

at the end of the file. fopen() creates the file if it does not exist.

Sample:

FILE* Archivo = fopen("Prueba.txt","r");

int Apariciones = 0; //! Es el contador

if (Archivo == NULL)

printf("\nError al intentar acceder al archivo");

else{

char TextoRecibido[1000];

char PalabraBuscada[] = "es"; //* Se sustituye por las palabras que elegiste

while (fscanf(Archivo,"%s",TextoRecibido) != EOF){

if (strcmp(TextoRecibido,PalabraBuscada) == 0)

Apariciones++;

}

}


fclose(Archivo);

printf("\nApariciones de la palabra: %d",Apariciones);


int fprintf(FILE *stream, const char *format, ...)

Sends formatted output to a stream.

Param stream: Pointer to a FILE object that identifies the stream.

Param format: String that contains the text to be written to the stream. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier (see 'printf' for tags).

Param additional aguments: Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter, if any. There should be the same number of these arguments as the number of %-tags that expect a value.

Returns Total number of characters written, if successful. A negative number otherwise.


int fputc(int char, FILE *stream)

Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream.


int fputs(const char *str, FILE *stream)

Writes a string to the specified stream up to but not including the null character.


int fscanf(FILE *stream, const char *format, ...)

It reads formatted input from a stream.

See fopen for an example.


int fseek(FILE *stream, long int offset, int whence)

Sets the file position of the stream to the given offset. The argument offset signifies the number of bytes to seek from the given whence position.

Param stream: Pointer to a FILE object that identifies the stream.

Param offset: Number of bytes to offset from whence.

Param whence: Position from where offset is added. It is specified by one of the following constants −

  • SEEK_SET Beginning of file

  • SEEK_CUR Current position of the file pointer

  • SEEK_END End of file

Returns zero if successful, or else it returns a non-zero value.


int getchar(void)

Returns the character read as an unsigned char cast to an int or EOF on end of file or error.

#include <stdio.h>


int main() {

int c,cont=0;


printf("Digite su nombre: y luego ctrl + z\n");

while (EOF != (c=getchar()))

{

switch (c)

{

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':cont++;

}

}

printf("El numero de vocales es: %i",cont);


return 0;

}


gets

Deprecated, use fgets w/ strtok instead.

See also scanf.

char name[40];

gets(name);


printf

See also puts.

printf("La suma es: %.2f\n", mysum); //Float w/ 2 decimal places

\n new line

\t tab


Format tags prototype is %[flags][width][.precision][length]specifier:

---- Flags ----

- Left-justifies within the given field width; Right justification is the default (see width sub-specifier).


+ Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign.

(space) If no sign is written, a blank space is inserted before the value.


# Used with o, x or X specifiers. The value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow then no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.


0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

---- Width ----

(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.


* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

---- .precision ----

.number For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.


.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

---- Length ----

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).


l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.


L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

---- specifier ----

c char


d signed decimal integer. W/ scanf %d assumes base 10 (012 would be 12).


e Scientific notation (mantissa/exponent) using e character


E Scientific notation (mantissa/exponent) using E character


f float


g Uses the shorter of %e or %f


G Uses the shorter of %E or %f


i int, unsigned int or short. W/ scanf %i detects the base (012 would be 10).

Hexadecimal is preceded w/ "0x" and octal w/ "0".


o Signed octal


s String of characters


u Unsigned decimal integer


x Unsigned hexadecimal integer


X Unsigned hexadecimal integer (capital letters)


p Pointer address in hexadeximal, data type (void *)


n Nothing printed


zu size_t (unsigned integer), appeared in C99


% Character


int putchar(int char)

Writes a character (an unsigned char) specified by the argument char to stdout.

Param char The character to be written. This is passed as its int promotion.

Return The character written as an unsigned char cast to an int or EOF on error.


puts

See also printf.

puts("Selecciona un numero de los dias de la semana (1 al 7)\n");


int remove(const char *filename)

Deletes the given filename so that it is no longer accessible.

Param filename String containing the name of the file to be deleted.

Return On success, zero. On error, -1, and errno is set appropriately.


void rewind(FILE *stream)

Sets the file position to the beginning of the file of the given stream.

Param stream Pointer to a FILE object that identifies the stream.


scanf

For string, see also gets.

scanf("%f %f", &num1, &num2); //Read 2 floats


Functions: stdlib.h

int atoi(const char *nptr)

Skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

Param nptr Pointer to a string to convert to an integer.

Return The integer representation of a string.


double atof(const char *nptr)

Skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

Param nptr Pointer to a string to convert to a floating-point number (double).

Return The floating-point representation of a string.


void *calloc(size_t nitems, size_t size)

Allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero.

Param nitems Number of elements to be allocated.

Param size Size of elements.

Return A pointer to the allocated memory, or NULL if the request fails.


void free(void *ptr)

Deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

Param ptr Pointer to a memory block previously allocated with malloc, calloc or realloc te be deallocated.

If a null pointer is passed as argument, no action occurs


void *malloc(size_t size)

Allocates the requested memory and returns a pointer to it. Function free is used to free it.

Param size Size of the memory block, in bytes

Return A pointer to the allocated memory, or NULL if the request fails.

#include <stdio.h>


int main() {

int* array;

array = (int*)malloc(4*8);

if (array != NULL)

printf("La memoria se ha otorgado\n");

else

printf("Error al adquirir la memoria\n");


int* array;

array = (int*)malloc(sizeof(int)*8);

if (array != NULL)

printf("La memoria se ha otorgado\n");

else

printf("Error al adquirir la memoria\n");

free(array);



#define SIZE 1000000


int* myArray = (int*)malloc(sizeof(int)*SIZE);

if (myArray == NULL)

printf("Se alcanzo el limite de memoria\n");

free(myArray);



return 0;

}


int rand(void)

Returns an integer value between 0 and RAND_MAX (which it's granted to be at least 32767).

See 'srand' function for an example.


void *realloc(void *ptr, size_t size)

Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

Param ptr Pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated.

If this is NULL, a new block is allocated and a pointer to it is returned by the function.

Param size The new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.

Return A pointer to the newly allocated memory, or NULL if the request fails.


void srand(unsigned int seed)

Param seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>


int main () {

int i, n;

time_t t;

n = 5;

/* Intializes random number generator */

srand((unsigned) time(&t));


/* Print 5 random numbers from 0 to 50 */

for( i = 0 ; i < n ; i++ ) {

printf("%d\n", rand() % 50);

}

return(0);

}


int system(const char *_Command)

system("clear"); //Clear screen (cls on Windows)

system("dir"); //SO command dir

system("PAUSE");


Functions: string.h

char *strcat(char *destination, const char *source)

It concatenates the destination string and the source string, and the result is stored in the destination string.

Note: The size of the destination string should be large enough to store the resultant string.


int strcmp (const char* str1, const char* str2)

0 if strings are equal

>0 if the first non-matching character in str1 is greater (in ASCII) than that of str2.

<0 if the first non-matching character in str1 is lower (in ASCII) than that of str2.


char* strcpy(char* destination, const char* source);

It copies the string pointed by source (including the null character) to the destination.

It returns the copied string.


size_t strlen(const char *str)

It takes a string as an argument and returns its length as type size_t (unsigned integer).

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};


// using the %zu format specifier to print size_t

printf("Length of string a = %zu \n",strlen(a)); // 7

printf("Length of string b = %zu \n",strlen(b)); // 7


char *strlwr(char *str)

It converts a given string into lowercase.


char *strrchr(const char *str, int c)

It searches for the last occurrence of the character c (an unsigned char) in the string pointed to, by the argument str.

It returns a pointer to the last occurrence of character in str. If the value is not found, the function returns a null pointer.

int len;

const char str[] = "http://www.tutorialspoint.com";

const char ch = '.';

char *ret;


ret = strrchr(str, ch);


printf("String after |%c| is - |%s|\n", ch, ret);

// String after |.| is - |.com|


char *strrev(char *str)

It reverses the given string.

It doesn't return anything but the reversed string is stored in the same string


char *strtok(char *str, const char *delim)

The contents of this string 'str' are modified and broken into smaller strings (tokens).

It returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.

char nombre[20];

fgets(nombre, 20, stdin);

strtok(nombre, "\n"); //Removes the trailing new line typed by the user


char *strupr(char *str)

It converts a given string into uppercase.


Functions: time.h

time_t time(time_t *seconds)

Parameter seconds is a pointer to an object of type time_t, where the seconds value will be stored.

It returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds.

time_t seconds = time(NULL);


time_t seconds;

// Stores time seconds

time(&seconds);



Functions: custom

#include <stdio.h>


void Mundo(); //Declare function before using it on 'main'


int main() {

Mundo();

return 0;

}


void Mundo(){

printf("Hola Mundo\n");

}


Operators

Aritméticos

+

-

*

/

%

++ Preincremento int b = ++a; Postincremento int b = a++;

--

Relational (operators)

==

!= If the two operands aren't equal

<

>

<=

>=

Lógicos

!

&&

||

Asignación

=

+= Suma y asignación. Eg: a += 3; is the same than a = a + 3;

-=

*=

/= Divide and assignment

%= Módulo y asignación

sizeof

Param Operand which size will be computed.

Return The amount of memory allocated, when it's used with data types.

#include <stdio.h>

int main() {

int a = 16;

printf("Size of variable a : %d

",sizeof(a));

printf("Size of int data type : %d

",sizeof(int));

printf("Size of char data type : %d

",sizeof(char));

printf("Size of float data type : %d

",sizeof(float));

printf("Size of double data type : %d

",sizeof(double));

return 0;

}


Flow control

if

Conditional.

int a,b;

a=b=3;

int c = a+b;


if (a+b == 6) {

printf("Result is %i", c);

} else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is true

} else {

// block of code to be executed if the condition1 is false and condition2 is false

}


switch

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed.

int day = 4;


switch (day) {

case 1:

printf("Monday");

break;

case 2:

printf("Tuesday");

break;

case 3:

printf("Wednesday");

break;

case 4:

printf("Thursday");

break;

case 5:

printf("Friday");

break;

case 6:

printf("Saturday");

break;

case 7:

printf("Sunday");

break;

}


// Outputs "Thursday" (day 4)


? ternary operator

int numero;

puts("Write a number\n");

scanf("%i, &numero);


(numero % 2 == 0) ? printf("El numero es par\n") : printf("El numero es impar\n");


for

Inline variable declaration only allowed in mode C99 or C11.

for (int i=0; i<10; i++) {

printf("* %i\n", i);

}


while

/* local variable definition */

int a = 10;


/* while loop execution */

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

}


do...while

It checks its condition at the botton of the loop; unlike for and while loops.

/* local variable definition */

int a = 10;


/* do loop execution */

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );



Algorithms search and traversal

Traversal over table (direct access)

TBD

Traversal over sequence

TBD

Search over table (direct access)

Generic search w/ direct access. The table isn't ordered so a sequential search is performed.

#include <stdio.h>


int main() {


int a[10]={2,4,6,8,0,1,3,5,7,9};

int i, dato;

char band = 'F';


printf("Escribe un numero\n");

scanf("%i",&dato);



i=0;

while ((band == 'F') && (i < 10)){

if (a[i] == dato){

band = 'V';

}

i++;

}


if (band == 'F'){

printf("El numero no existe en la lista\n");

}else if (band == 'V'){

printf("El numero existe, en la posicion %i ",i-1);

}


return 0;

}

Search over sequence

TBD

Algorithms: order array using bubble method, and binary search it

It orders and array of integers, ascending and then it performs a binary search on it.

#include <stdio.h>


int main() {


int a[10] = {1,3,5,7,9,2,4,6,8,10};

int i,j,aux,dato,inf,sup,mitad;

char band = 'F';


//Metodo burbuja


for (i = 0; i < 10; i++){

for (j = 0; j < 10; j++){

if (a[j] > a[j+1]){

aux = a[j];

a[j] = a[j+1];

a[j+1] = aux;

}

}

}


for (i = 0; i < 10; i++){

printf("%i, ",a[i]);

}


printf("\nEscribe un numero: ");

scanf("%i",&dato);


//Busqueda Binaria


inf = 0;

sup = 10;


while (inf <= sup){

mitad = (inf+sup)/2;


if (a[mitad] == dato){

band = 'V';

break;

}

if (a[mitad] > dato){

sup = mitad;

mitad = (inf+sup)/2;

}

if (a[mitad] < dato){

inf = mitad;

mitad = (inf+sup)/2;

}

}


if (band == 'F'){

printf("El numero no existe\n");

}else if (band == 'V'){

printf("El numero existe en la posicion %i",mitad);

}

return 0;

}


Sample: Hello world!

#include <stdio.h>


int main(){

printf("Hola Mundo");

return 0;

}

Sample: Arrays always passed by reference

#include <stdio.h>


//* Esta Funcion Recibe un Array y lo llena

//! Nota que no se indica el numero de indices que recibira, se hace con otra variable


void llenarArray(int Array[],int dimension){

for(int i = 0; i<dimension;i++){

printf("\nDame el valor [%d] del array",i);

scanf("%d",&Array[i]);

}

}



int main() {


int miVector[5];

//* Solo pasamos el nombre del array y su dimension

llenarArray(miVector,5);

//! Imprimimos sus valores


//? Recuerda que por defecto el array se hace con paso de parametros por referencia

//? Esto nos permite editarlo desde otra funcion


for (int x = 0; x < 5; x++){

printf("%d",miVector[x]);

}


return 0;

}

Sample: Pointer to array

#include <stdio.h>


int main() {

//*Declaramos un array de 5 indices

int array[5] = {1,2,3,4,5};


//! Ahora un apuntador al inicio de la variable

int* apuntadorArray = &array[0];


//* Con esto podemos desplazarnos por el array sin conocer su dimension

while (*apuntadorArray != NULL){

printf("\n %d",*apuntadorArray);

apuntadorArray++; //! Se va recorriendo el array por las posiciones

}


return 0;

}