Created
June 27, 2017 03:40
-
-
Save aipi/525cd88bf1b05ab6aebccf83163d41db to your computer and use it in GitHub Desktop.
Example to dynamic memory alocation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int *realoca(int *ptr, int *size) { | |
int add; | |
printf("Insira quantos números quer alocar:\n"); | |
scanf("%d", &add); | |
ptr = (int *) realloc(ptr, (*size + add) * sizeof(int)); | |
if(ptr){ | |
for (int i = 0; i < add; i++) { | |
printf("Insira os valores desejados:\n"); | |
scanf("%d", &ptr[*size+i]); | |
} | |
*size += add; | |
} else { | |
printf("Quantidade de memória não compatível\n"); | |
free(ptr); | |
exit(1); | |
}; | |
return ptr; | |
} | |
void exibir(int *ptr, int size) { | |
printf("\n--------------\n"); | |
for (int i = 0; i < size; i++) { | |
printf("%d\n", ptr[i]); | |
} | |
printf("--------------\n"); | |
} | |
void media(int *ptr, int size) { | |
float media = 0.0; | |
printf("A média da soma do seguintes números: "); | |
for (int i = 0; i < size; i++){ | |
if(i == size-1){ | |
printf("%d ", ptr[i]); | |
}else{ | |
printf("%d, ", ptr[i]); | |
} | |
media += ptr[i]; | |
} | |
printf("é %.1f\n", media); | |
} | |
int menu() { | |
int opcao; | |
printf("Insira uma das opções:\n"); | |
printf("0 - Sair\n"); | |
printf("1 - Inserir\n"); | |
printf("2 - Listar\n"); | |
printf("3 - Listar Média\n"); | |
printf("Opção: "); | |
scanf("%d", &opcao); | |
return opcao; | |
} | |
int main(void) { | |
int *ptr = NULL, size = 0, opcao=4; | |
while(opcao != 0) { | |
switch(menu()){ | |
case 0: | |
opcao=0; | |
break; | |
case 1: | |
ptr = realoca(ptr, &size); | |
break; | |
case 2: | |
exibir(ptr, size); | |
break; | |
case 3: | |
media(ptr,size); | |
break; | |
default: | |
printf("Opção inválida!\n"); | |
} | |
} | |
free(ptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment