0% found this document useful (0 votes)
46 views36 pages

Modulo 5

This document contains code examples demonstrating the use of pointers in C programming. It includes examples of pointer perils like using uninitialized pointers, buffer overflows, and accessing memory outside of arrays. It also shows proper usage of pointers with dynamic memory allocation functions like malloc() and free(). Functions, parameters, and returning values are demonstrated. Arrays of pointers are used to represent multi-dimensional arrays and matrices.

Uploaded by

HUNTER Y TANK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
46 views36 pages

Modulo 5

This document contains code examples demonstrating the use of pointers in C programming. It includes examples of pointer perils like using uninitialized pointers, buffer overflows, and accessing memory outside of arrays. It also shows proper usage of pointers with dynamic memory allocation functions like malloc() and free(). Functions, parameters, and returning values are demonstrated. Arrays of pointers are used to represent multi-dimensional arrays and matrices.

Uploaded by

HUNTER Y TANK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

Universidad Tecnológica de Querétaro

DTAI. TSU en Mecatrónica-Area de automatización

Módulo 5 - operaciones avanzadas sobre matrices y punteros, gestión de memoria y


conceptos básicos de funciones herramienta externas

Lenguaje de programación
Alumno:
Alan Eduardo Ortega Herrera

Grupo:
E187

Profesor:

Yara Odeth Sainz García.


Fecha:
Octubre 06 del 2023.
 5.1.2.1 Using pointers: perils and disadvantages
Código:

#include <stdio.h>
#include <string.h>

int main(void) {
char *ptr;
strcpy(ptr, "you may get into trouble soon");
puts(ptr);
return 0;
}

 5.1.2.2 Using pointers: perils and disadvantages


Código:

#include <stdio.h>
int main(void) {
char *ptr;
*ptr = 'C';
printf("%c",*ptr);
return 0;
}
 5.1.2.3 Using pointers: perils and disadvantages
Código:

#include <stdio.h>
#include <string.h>

int main(void) {
char str[10];

strcpy(str,"Welcome to Troubleland!");
printf("%s",str);
return 0;
}
 5.1.2.4 Using pointers: perils and disadvantages
Código:

#include <stdio.h>
#include <string.h>

int main(void) {
char str[10];
int i;

strcat(str,"Bump!");
printf("%s",str);
return 0;
}

 5.1.3.3 Using pointers: perils and disadvantages


Código:

float temp[31][24];
int day;
float sum = 0.0, average;

for(day = 0; day < 31; day++)


sum += temp[day][11];
average = sum / 31;
printf("Average temperature at noon: %f", average);

 5.1.3.4 Using pointers: perils and disadvantages


Código:

float temp[31][24];
int day,hour;
float max = -100.0;

for(day = 0; day < 31; day++)


for(hour = 0; hour < 24; hour++)
if(temp[day][hour] > max)
max = temp[day][hour];
printf("The highest temperature was %f", max);
 5.1.3.5 Using pointers: perils and disadvantages
Código:

float temp[31][24];
int day,hour;
int hotdays = 0;

for(day = 0; day < 31; day++)


if(temp[day][11] >= 20.0)
hotdays++;
printf("%d days were hot.", hotdays);
 5.1.3.6 Using pointers: perils and disadvantages
Código:

float temp[31][24];
int d,h;

for(d = 0; d < 31; d++)


for(h = 0; h < 24; h++)
temp[d][h] = 0.0;

 5.1.3.8 LAB: Not only vectors: chessboard


Código:

#include <stdio.h>

int main(void)
{
char board[8][8];
int i;

board[0][0] = 'R';
board[0][1] = 'N';
board[0][2] = 'B';
board[0][3] = 'Q';
board[0][4] = 'K';
board[0][5] = 'B';
board[0][6] = 'N';
board[0][7] = 'R';
board[7][0] = 'R';
board[7][1] = 'N';
board[7][2] = 'B';
board[7][3] = 'Q';
board[7][4] = 'K';
board[7][5] = 'B';
board[7][6] = 'N';
board[7][7] = 'R';

for (i = 0; i < 8; i++)


{
board[1][i] = 'P';
board[2][i] = ' ';
board[3][i] = ' ';
board[4][i] = ' ';
board[5][i] = ' ';
board[6][i] = 'P';
}
int j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
return 0;
}
 5.1.3.9 LAB: Indexing vs pointers
Código:

#include <stdio.h>

int main(void)
{
char days[7][10] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"};
int day;

scanf("%d", &day);
if (day >= 0 && day < 7)
{
printf("Pointer version: %s\n", days + day);
printf("Array index version: %s\n", days[day]);
}
else
puts("Error, no such day.");
return 0;
}
 5.1.4.4 Memory allocation and deallocation: malloc() and free()
Código:

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

int main(void) {
int *ptr;

ptr = (int *) malloc(sizeof(int));


if(ptr != NULL) {
*ptr = 200;
printf("ptr points to value of %d", *ptr);
free(ptr);
} else
printf("allocation failed");
return 0;
}
 5.1.4.5 Memory allocation and deallocation: malloc() and free()
Código:

int *tabptr, i, sum = 0;

tabptr = (int *) malloc(5 * sizeof(int));


for(i = 0; i < 5; i++)
tabptr[i] = i;
sum = 0;
for(i = 0; i < 5; i++)
sum += tabptr[i];
free(tabptr);
 5.1.4.6 Memory allocation and deallocation: malloc() and free()
Código:

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

int main(void) {
int *numbers, how_many_numbers;
int i, aux;
int swapped;

printf("How many numbers are you going to sort?");


scanf("%d", &how_many_numbers);
if( how_many_numbers <= 0 || how_many_numbers > 1000000) {
printf("Are you kidding?\n");
return 1;
}
numbers = (int *) malloc(how_many_numbers * sizeof(int));
if(numbers == NULL) {
printf("Allocation failed – sorry.\n");
return 1;
}
for(i = 0; i < how_many_numbers; i++) {
printf("\nEnter the number #%i:\n",i + 1);
scanf("%d",numbers + i);
}
do {
swapped = 0;
for(i = 0; i < how_many_numbers - 1; i++)
if(numbers[i] > numbers[i + 1]) {
swapped = 1;
aux = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = aux;
}
} while(swapped);
printf("\nThe sorted array:\n");
for(i = 0; i < how_many_numbers; i++)
printf("%d ",numbers[i]);
printf("\n");
free(numbers);
return 0;
}
 5.1.4.7 LAB: Memory on demand
 Código:

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

int main(void)
{
int size;

scanf("%d", &size);

if(size>=1024*1024)
{
puts("Too much memory requested.");
}
else
{
char *values=(char *) malloc (sizeof(char) * size) ;
int i;
for(i=0 ; i < size ; i++)
{
values[i] = 'A' + (i % 26);
}
int boundaries = size;
if (boundaries > 400)
boundaries = 400;
for (i=0 ; i < boundaries ; i++)
{
printf("%c", values[i]);
if ((i+1) % 40 == 0)
printf("\n");
}
printf("\n");
}
return 0;
}

 5.1.5.3 Arrays of pointers as multidimensional arrays


 Código:

int **ptrtab;

 5.1.5.4 Arrays of pointers as multidimensional arrays


 Código:

ptrtab = (int **) malloc (rows * sizeof (int*));


 5.1.5.5 Arrays of pointers as multidimensional arrays
 Código:

for (r = 0; r <rows; r++)


ptrtab[r] = (int *) malloc (cols * sizeof (int));

 5.1.6.2 LAB: Arrays of pointers: matrices


Código:

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

int main(void)
{
int size;
scanf("%d", &size);
if(size>20)
{
puts("Matrix too big.");
}
else
{
int **matrix = (int**)malloc(sizeof(int *) * size);
int i, j;
for (i=0; i < size ; i++)
{
matrix[i] = (int*)malloc(sizeof(int) * size);
}

for (i = 0; i<size; i++)


{
for (j = 0; j<size; j++)
{
matrix[i][j] = (i + 1)*(j + 1);
}
}
printf("%4c", ' ');
for (j = 0; j<size; j++)
{
printf("%4d", j+1);
}
printf("\n");
for (i = 0; i<size; i++)
{
printf("%4d", i+1);
for (j = 0; j<size; j++)
{
printf("%4d", matrix[i][j]);
}
printf("\n");
}
for (i = 0; i < size; i++)
{
free(matrix[i]);
}
free(matrix);

}
return 0;
}

 5.1.8.2 Our first function


Código:

int CountSheep(void); /* declaration */

int CountSheep(void) { /* definition */


return ++SheepCounter;
}
 5.1.8.4 Our first function
Código:

int CountSheep(void); /* declaration */

int CountSheep(void) { /* definition */


return ++SheepCounter;
}
 5.1.8.5 Our first function
Código:

#include <stdio.h>

void hello(void);

int main(void) {
printf("We are about to invoke hello()!\n");
hello();
printf("We returned from hello()!\n");
return 0;
}

void hello(void) {
printf ("You've invoked me – what fun!\n");
return;
}

 5.1.9.2 Variables, parameters and results


Código:

#include <stdio.h>
void hello(void) {
int i;

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


printf ("You've invoked me – what fun!\n");
return;
}
int main(void) {
int i;
printf("We are about to invoke hello()!\n");
for(i = 0; i < 3; i++)
hello();
printf("We returned from hello()!\n");
return 0;
}

 5.1.9.3 Variables, parameters and results


Código:

#include <stdio.h>

int global;

void fun(void) {
int local;

local = 2;
global++;
printf("fun: local=%d global=%d\n", local, global);
global++;
}

int main(void) {
int local;

local = 1;
global = 1;
printf("main: local=%d global=%d\n", local, global);
fun();
printf("main: local=%d global=%d\n", local, global);
return 0;
}

 5.1.9.5 Variables, parameters and results


Código:

int notmany = 5;
hello2(100); /* the actual parameter is a literal */
hello2(notmany); /* the actual parameter is a variable */
hello2(2 * notmany); /* the actual parameter is an expression */

 5.1.9.7 Variables, parameters and results


Código:

void hello2(int times) {


int i;
for(i = 0; i < times; i++)
printf ("You've invoked me – what fun!\n");
return;
}
 5.1.9.7 Variables, parameters and results
Código:

void hello2(int times) {


int i;
for(i = 0; i < times; i++)
printf ("You've invoked me – what fun!\n");
return;
}

 5.1.9.8 Variables, parameters and results


Código:

#include <math.h>
#include <stdio.h>

int main(void) {
float a, b, a_sqr, b_sqr, c;

printf("A?\n");
scanf("%f", &a);
a_sqr = a * a;
printf("B?\n");
scanf("%f", &b);
b_sqr = b * b;
c = sqrt(a_sqr + b_sqr);
printf("The length of the hypotenuse is: %f\n", c);
return 0;
}

 5.1.9.10 Variables, parameters and results


Código:

#include <math.h>
#include <stdio.h>

float square(float param) {


return param * param;
}

int main(void) {
float a, b, a_sqr, b_sqr, c;

printf("A?\n");
scanf("%f", &a);
a_sqr = square(a);
printf("B?\n");
scanf("%f", &b);
b_sqr = square(b);
c = sqrt(a_sqr + b_sqr);
printf("The length of the hypotenuse is: %f\n", c);
return 0;
}

 5.1.9.12 LAB: Functions: Part 1 - Function call


Código:

#include <stdio.h>

void hello()
{
puts("Hello!");
}
void another()
{
puts("It's me - another function.");
}

int main(void)
{
hello();
hello();
hello();
another();
hello();
another();
return 0;
}

 5.1.9.13 LAB: Functions: Part 2 - Function call


Código:

#include <stdio.h>

int getValue(int paramA, float paramB)


{
int result = 0;
if (paramA>10)
{
result += 2;
}
else
{
result += 1;
}
if (paramB>5.5)
{
result += 4;
}
else
{
result += 3;
}
return result;
}

int getOneOrTwo(int param)


{
if(param > 5)
return 2;
return 1;
}

int main(void)
{
int fiveValue = getValue(1, 5.6);
int sixValue = getValue(11, 5.6);
int sevenValue = getValue(11, 5.6) + getOneOrTwo(0);
int eightValue = getValue(11, 5.6) + getOneOrTwo(6);
int nineValue = getValue(11, 5.6) + getOneOrTwo(0) + getOneOrTwo(6);

printf("Five: %d\n", fiveValue);


printf("Six: %d\n", sixValue);
printf("Seven: %d\n", sevenValue);
printf("Eight: %d\n", eightValue);
printf("Nine: %d\n", nineValue);
return 0;
}
 5.1.9.14 LAB: Functions: Part 3 - Function call
Código:

#include <stdio.h>

double getMaxOfThree(double paramA, double paramB, double paramC)


{
if (paramA > paramB && paramA > paramC)
return paramA;
if (paramB > paramA && paramB > paramC)
return paramB;
return paramC;
}

int main(void)
{
double tenValue = getMaxOfThree(5, 9, 10);
double bigValue = getMaxOfThree(555.4, 555.3, 556.4);
printf("Ten: %.2f\n", tenValue);
printf("Big value: %.2f\n", bigValue);
return 0;
}
 5.1.9.15 LAB: Functions: Part 4 - Function call
Código:

#include <stdio.h>

double power(double, int );

int main(void)
{
double twentyFiveValue = power(5.0, 2);
double piSquaredValue = power(3.14159265, 2);
double piCubedValue = power(3.14159265, 3);
double bigPower = power(1.23, 20);
double millionValue = power(10, 6);

printf("Thirty five: %.4f\n", twentyFiveValue);


printf("Pi squared: %.4f\n", piSquaredValue);
printf("Pi cubed: %.4f\n", piCubedValue);
printf("Not so big number: %.4f\n", bigPower);
printf("Million: %.4f\n", millionValue);
return 0;
}
double power(double base, int exponent)
{
double result = 1;
for (int i = 0; i < exponent; i++)
{
result *= base;
}
return result;
}

 5.1.9.16 LAB: Functions: Part 5 - Function call


Código:

#include <stdio.h>

int getValue(int paramA, float paramB);


int getExclusive(int paramA, int paramB);

int main(void)
{
int thirtyFiveValue = getValue(4, 2.4);
int thirtyValue1 = getValue(4, 2.6);
int thirtyValue2 = getValue(6, 2.4);
int twentyValue = getValue(6, 2.6);
int twoValue = getExclusive(2, 1);
int zeroValue = getExclusive(2, 2);

printf("Thirty five: %d\n", thirtyFiveValue);


printf("Thirty: %d\n", thirtyValue1);
printf("Thirty: %d\n", thirtyValue2);
printf("Twenty: %d\n", twentyValue);
printf("Two: %d\n", twoValue);
printf("Zero: %d\n", zeroValue);
return 0;
}

int getValue(int paramA, float paramB)


{
int result = 0;
if (paramA>=5)
{
result += 5;
}
else
{
result += 10;
}
if (paramB>=2.5)
{
result += 20;
}
else
{
result += 25;
}
return result;
}
int getExclusive(int paramA, int paramB)
{
if (paramA == 2 && paramB != 2)
return 2;
if (paramA != 2 && paramB == 2)
return 2;
return 0;
}

 5.1.9.17 LAB: Functions: Part 6 - Function call


Código:

#include <stdio.h>

int stringCompare(char *strA, char *strB)


{
int i;
for (i=0 ; strA[i] != 0 && strB[i] != 0 ; i++)
{
if(strA[i]>strB[i])
{
return 1;
}
else if (strA[i] < strB[i])
{
return -1;
}
}
if (strA[i] == 0)
{
if (strB[i] == 0)
return 0;
else
return -1;
}
else
return 1;
}

int main(void)
{
int result1 = stringCompare("AAA", "BBB");
int result2 = stringCompare("AAC", "AAB");
int result3 = stringCompare("AAC", "AAC");
int result4 = stringCompare("AAC", "AACC");

printf("result1: %d\n", result1);


printf("result2: %d\n", result2);
printf("result3: %d\n", result3);
printf("result4: %d\n", result4);
return 0;
}

You might also like