PuPax Posted May 15, 2008 at 01:51 PM Report Share #185290 Posted May 15, 2008 at 01:51 PM Boa tarde, Alguem pode deixar aqui como criar um array multidimensional dinamico. Por exemplo as linhas têm de ter 100 caracteres, e as colunas sao criadas dinamicamente conforme os nomes, isto é, a medida que o programa corre adiciono um nome ao array. Link to comment Share on other sites More sharing options...
Baderous Posted May 15, 2008 at 02:41 PM Report Share #185293 Posted May 15, 2008 at 02:41 PM Tens de criar um array de apontadores (para o tipo que queres) e depois fazes a alocação dinâmica de memória. char *array[100]; array[i] = (char*)malloc(sizeof(char)*dim); onde dim é a dimensão de cada string que vais ter no array. Link to comment Share on other sites More sharing options...
Rui Carlos Posted May 15, 2008 at 03:08 PM Report Share #185295 Posted May 15, 2008 at 03:08 PM Ou crias um array de arrays (que foi o que o Baderous sugeriu), ou vais ter que andar com conversões de índices e inverter a organização habitual dos elementos (em vez de uma linha estar em posições consecutivas, estão os elementos de uma coluna), pois para a posição de memória de um elemento não mudar, precisas de ter o número de colunas fixo (é claro que aquilo a que chama linha e coluna é apenas uma convenção, que podes trocar sem qualquer problema). Rui Carlos Gonçalves Link to comment Share on other sites More sharing options...
Rui Carlos Posted May 15, 2008 at 03:30 PM Report Share #185300 Posted May 15, 2008 at 03:30 PM Estás a alocar o espaço, mas não estás a copiar os dados. E podes usar o strdup. Rui Carlos Gonçalves Link to comment Share on other sites More sharing options...
Baderous Posted May 15, 2008 at 03:32 PM Report Share #185301 Posted May 15, 2008 at 03:32 PM Estás a alocar o espaço, mas não estás a copiar os dados. E podes usar o strdup. Ya, apaguei o post porque reparei na estupidez que tinha feito. EDIT: Aqui fica o código já correcto. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 #define SU 200 int main() { char* array[MAX]; char nome[sU]; int i; for (i=0;i<MAX;i++) { printf("Introduza a string: "); fgets(nome,SU,stdin); nome[strlen(nome)-1]='\0'; array[i]=strdup(nome); } for (i=0;i<MAX;i++) printf("%s\n",array[i]); return 0; } Link to comment Share on other sites More sharing options...
Rui Carlos Posted May 15, 2008 at 03:44 PM Report Share #185305 Posted May 15, 2008 at 03:44 PM Com o strdup deixas de precisar de alocar o espaço para a string. Rui Carlos Gonçalves Link to comment Share on other sites More sharing options...
Baderous Posted May 15, 2008 at 03:53 PM Report Share #185307 Posted May 15, 2008 at 03:53 PM Com o strdup deixas de precisar de alocar o espaço para a string. Não sabia dessa. Então strdup é quase que um malloc + strcpy. Link to comment Share on other sites More sharing options...
bertolo Posted August 22, 2008 at 01:05 PM Report Share #206367 Posted August 22, 2008 at 01:05 PM cria listas de listas depois crias algumas funçoes para eliminar, apagar e editar e ta feito. Link to comment Share on other sites More sharing options...
mrentes Posted August 28, 2008 at 01:09 PM Report Share #207357 Posted August 28, 2008 at 01:09 PM Depois do strdup, no fim do programa, convém libertar a memória alocada com o free. Link to comment Share on other sites More sharing options...
Rui Carlos Posted August 28, 2008 at 01:30 PM Report Share #207364 Posted August 28, 2008 at 01:30 PM Depois do strdup, no fim do programa, convém libertar a memória alocada com o free. No caso do código do Baderous não há qualquer necessidade de o fazer pois o programa termina de seguida. Rui Carlos Gonçalves Link to comment Share on other sites More sharing options...
mrentes Posted August 28, 2008 at 01:53 PM Report Share #207382 Posted August 28, 2008 at 01:53 PM OK, mas é boa prática fazê-lo, não concordas? Link to comment Share on other sites More sharing options...
Rui Carlos Posted August 28, 2008 at 01:58 PM Report Share #207383 Posted August 28, 2008 at 01:58 PM Sim, é uma boa prática. Lembro-me que nos trabalhos da univ tinha que o fazer mesmo quando encerrava o programa a seguir. E normalmente eram estruturas de dados bem mais complexa. Mas nestes casos, numa aplicação real, provavelmente não o faria. Aqui é apenas uma questão de incutir um hábito necessário em muitas situações. Rui Carlos Gonçalves Link to comment Share on other sites More sharing options...
i307 Posted May 23, 2011 at 11:57 PM Report Share #390321 Posted May 23, 2011 at 11:57 PM Precisava de alocar memória para um vector multi dimensional mas recebendo as 2 variáveis in run time. Qual a melhor maneira de o fazer? int l , c ; int *v; int i=0,j=0; printf("Linhas:"); scanf("%i",&l); printf("Colunas:"); scanf("%i",&c); v[l] = (int**) malloc(sizeof(int*)* l ); v[c] = (int**) malloc(sizeof(int*)* c ); printf("Preencha as colunas %ix%i\n",l,c); for(i=0;i<l;i++){ for(j=0;j<c;j++){ scanf("%i",v[i][j]); } } Link to comment Share on other sites More sharing options...
Baderous Posted May 24, 2011 at 12:09 AM Report Share #390324 Posted May 24, 2011 at 12:09 AM Tens exemplos aqui: http://www.portugal-a-programar.pt/index.php?showtopic=43975 Link to comment Share on other sites More sharing options...
i307 Posted May 24, 2011 at 12:12 AM Report Share #390325 Posted May 24, 2011 at 12:12 AM Tens exemplos aqui: http://www.portugal-a-programar.pt/index.php?showtopic=43975 Pois , eu encontrei o tópico no google e só reparei depois que havia um tópico tão fresquinho. Link to comment Share on other sites More sharing options...
i307 Posted May 24, 2011 at 12:36 AM Report Share #390328 Posted May 24, 2011 at 12:36 AM Como passar um vector bidimensional para dentro duma função? No livro do Luís Damas está "A passagem de vectores com mais dimensão (...) obrigatoriamente , o nº de elementos de cada uma das n-1 dimensões à direita (...)" Só que eu quero passar o vector para dentro da função e só em run time é que o programa sabe as dimensões. Não está a funcionar (e enquanto estava com memória estática funcionava): printf("Linhas:"); scanf("%i",&l); printf("Colunas:"); scanf("%i",&c); v = (int**) malloc(sizeof(int*)* l ); for (i=0; i<l; i++) { v[i] = (int *) malloc(sizeof(int*)* c ); for (j = 0; j < c; j++){ v[i][j] = j + 1; } } Até aqui recebe os valores e mostra sem problema. Mas depois: troca(v,l,c); (...) void troca (int **vect, int linhas , int colunas) { int temp, k, pass; int trocou = 1; int l=0; int i=0,j=0; while(l<linhas){ for (pass=0; pass<linhas-1 && trocou; pass++) { trocou = 0; for (k = 0; k < linhas-pass-1; k++) /* bubble sort */ if (vect[l][k] > vect[l][k+1]) { trocou = 1; ; temp = vect[l][k]; vect[l][k] = vect[l][k+1]; vect[l][k+1] = temp; } l++; } } Dá segmentation fault. Link to comment Share on other sites More sharing options...
Baderous Posted May 24, 2011 at 12:59 AM Report Share #390330 Posted May 24, 2011 at 12:59 AM Testei isso e correu bem, a única coisa que detectei é que o bubble sort não está a ordenar o último valor das linhas: #include <stdio.h> #include <stdlib.h> void troca (int **vect, int linhas , int colunas) { int temp, k, pass; int trocou = 1, l; for (l=0;l<linhas;l++) { for (pass=0; pass<linhas-1 && trocou; pass++) { trocou = 0; for (k = 0; k < linhas-pass-1; k++) /* bubble sort */ if (vect[l][k] > vect[l][k+1]) { trocou = 1; ; temp = vect[l][k]; vect[l][k] = vect[l][k+1]; vect[l][k+1] = temp; } } } } void print(int **v, int l, int c) { int i,j; for (i=0;i<l;i++) { for (j=0;j<c;j++) printf("%d ",v[i][j]); putchar('\n'); } } int main(void) { int l,c,i,j; int **v; printf("Linhas:"); scanf("%d",&l); scanf("%*c"); printf("Colunas:"); scanf("%d",&c); v = (int**) malloc(sizeof(int*)* l ); for (i=0; i<l; i++) { v[i] = (int *) malloc(sizeof(int*)* c ); for (j = 0; j < c; j++) { v[i][j] = 20 - j + 1; } } print(v,l,c); troca(v,l,c); print(v,l,c); return 0; } Link to comment Share on other sites More sharing options...
i307 Posted May 24, 2011 at 02:07 AM Report Share #390336 Posted May 24, 2011 at 02:07 AM Mas isso é secundário. É que dá-me Segmentation Fault. Diz que é nesta linha if (vect[l][k] > vect[l][k+1]) EDIT: criei projecto novo e já deu bem. Só está é a ordenar a 1ª linha. Mas isto agora tenho de ver. Link to comment Share on other sites More sharing options...
Baderous Posted May 24, 2011 at 02:12 AM Report Share #390338 Posted May 24, 2011 at 02:12 AM Usa um debugger como o GDB para ver o que se passa. Link to comment Share on other sites More sharing options...
i307 Posted May 24, 2011 at 10:48 AM Report Share #390415 Posted May 24, 2011 at 10:48 AM Não estou a ver o problema . Estive a verificar e supostamente havia de fazer as trocas mas apenas troca a 1ª linha. Apesar de dar para ver a var temp os outros valores. ocou = 1, l; for (l=0;l<linhas;l++) { for (pass=0; pass<linhas-1 && trocou; pass++) { trocou = 0; for (k = 0; k < linhas-pass-1; k++) /* bubble sort */ if (vect[l][k] > vect[l][k+1]) { trocou = 1; ; temp = vect[l][k]; vect[l][k] = vect[l][k+1]; vect[l][k+1] = temp; } } } } Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now