Baixe o app para aproveitar ainda mais
Prévia do material em texto
The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have Alocação Dinâmica de Memória Gisele L. Pappa Algoritmos e Estruturas de Dados II DCC – UFMG The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Alocação Estática x Dinâmica n C: dois tipos de alocação de memória: Estática e Dinâmica n Na alocação estática, o espaço para as variáveis é reservado no início da execução, não podendo ser alterado depois q int a; int b[20]; n Na alocação dinâmica, o espaço para as variáveis pode ser alocado dinamicamente durante a execução do programa The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Organização da Memória Algoritmos e Estrutura de Dados II Informação sobre funções Código compilado Memória Dinâmica The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Alocação Dinâmica n As variáveis alocadas dinamicamente são chamadas de Apontadores (pointers) pois na verdade elas armazenam o endereço de memória de uma variável n A memória alocada dinamicamente faz parte de uma área de memória chamada heap q Basicamente, o programa aloca e desaloca porções de memória do heap durante a execução The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Esquema de Memória Memória Estática 0x016 a 0x020 b 10 0X234 10 a é um int b é um apontador para um int Heap 0X214 0X218 0X222 0X226 0X230 0X234 0X238 0X240 The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Acesso a partir de Apontadores n Acessar o valor da variável: endereço de memória armazenado n Acessar o conteúdo que associado ao endereço de memória armazenado The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Liberação de Memória n A memória deve ser liberada após o término de seu uso n A liberação deve ser feita por quem fez a alocação: q Estática: compilador q Dinâmica: programador The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Apontadores – Notação n definição de p como um apontador para uma variável do tipo Tipo q Tipo *p; n Alocação de memória para uma variável apontada por p q p = (Tipo*) malloc(sizeof(Tipo)); n Liberação de memória q free(p); n Conteudo da variável apontada por P q *p; n Valor nulo para um apontador q NULL; n Endereço de uma variável a q &a; The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Alocação Dinâmica int *a, b; ... b = 10; a = (int *) malloc(sizeof(int)); *a = 20; a = &b; a 20 b Heap Alocação Estática 10 X The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Alocação Dinâmica int b; int *a; b = 10; a = (int *) malloc(sizeof(int)); *a = 20; printf("%d\n", a[0]); a = &b; printf("%d\n", a[0]); The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Erros Comuns n Esquecer de alocar memória e tentar acessar o conteúdo da variável n Copiar o valor do apontador ao invés do valor da variável apontada n Esquecer de desalocar memória q Ela é desalocada ao fim do programa ou procedimento função onde a variável está declarada, mas pode ser um problema em loops n Tentar acessar o conteúdo da variável depois de desalocá-la The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Exercício: C double a; double *p; a = 3.14; printf("%f\n", a); p = &a; *p = 2.718; printf("%f\n", a); a = 5; printf("%f\n", *p); p = NULL; p = (double *)malloc(sizeof(double)); *p = 20; printf("%f\n", *p); printf("%f\n", a); free(p); printf("%f\n", *p); The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Pergunta que não quer calar... int *a não é a declaração de um vetor de int? n Em C, todo vetor é um apontador. n Portanto pode-se fazer coisas como: int a[10], *b; b = a; b[5] = 100; printf(“%d\n”, a[5]); printf(“%d\n”, b[5]); int a[10], *b; b = (int *) malloc(10*sizeof(int)); b[5] = 100; printf(“%d\n”, a[5]); Printf(“%d\n”, b[5]); 100 100 42657 100 Obs. Não se pode fazer a = b no exemplo acima The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Apontadores para Tipos Estruturados n Apontadores são normalmente utilizados com tipos estruturados Typedef struct { int idade; double salario; } TRegistro TRegistro *a; ... a = (TRegistro *) malloc(sizeof(TRegistro))a->idade = 30; /* *a.idade = 30 */ a->salario = 80; The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Passagem de Parâmetros n Em pascal, parâmetros para função podem ser passados por valor ou por referência q Por valor: o parâmetro formal (recebido no procedimento) é uma cópia do parâmetro real (passado na chamada) q Por referência: o parâmetro formal (recebido no procedimento) é uma referência para o parâmetro real (passado na chamada) q Usa-se o termo var precedendo o parâmetro formal n Em C só existe passagem por valor, logo deve-se implementar a passagem por referência utilizando- se apontadores The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Passagem de Parâmetros (C) void SomaUm(int x, int *y) { x = x + 1; *y = (*y) + 1; printf("Funcao SomaUm: %d %d\n", x, *y); } int main() { int a=0, b=0; SomaUm(a, &b); printf("Programa principal: %d %d\n", a, b); } 1 1 0 1 The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Passagem de Parâmetros n E para alocar memória dentro de um procedimento? q Em pascal, basta passar a variável (apontador) como referência. q Em C também, mas como não há passagem por referência as coisas são um pouco mais complicadas void aloca(int *x, int n) { x=(int *)malloc(n*sizeof(int)); x[0] = 20; } int main() { int *a; aloca(a, 10); a[1] = 40; } Error! Access Violation! void aloca(int **x, int n) { *x=(int *)malloc(n*sizeof(int)); *x[0] = 20; } int main() { int *a; aloca(&a, 10); a[1] = 40; } OK The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the The ima ge can not be disp laye d. Algoritmos e Estrutura de Dados II Exercício n Criar um tipo que é uma estrutura que represente uma pessoa, contendo nome, data de nascimento e CPF. n Criar uma variável que é um ponteiro para esta estrutura (no programa principal) n Criar uma função que recebe este ponteiro e preenche os dados da estrutura n Criar uma função que recebe este ponteiro e imprime os dados da estrutura n Fazer a chamada a esta função na função principal
Compartilhar