Array of pointers with struct

1

I am trying to assign 3 names to a string vector within a struct, and using pointers to reference the dynamically allocated struct, and then print and reverse it in a repeat structure, but when trying to print it it is not returned nothing.

String to be printed

printf("%s\n",*(*p).vet[1]); Ana
printf("%s\n",*(*p).vet[2]); Bia 
printf("%s\n",*(*p).vet[3]); Lia

Inverted String

   printf("%c\n",*(*q).vet[1]); a+n+A 
   printf("%c\n",*(*q).vet[2]); a+i+B
   printf("%c\n",*(*q).vet[3]); a+i+L

Code

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

typedef struct elemento *ponteiro;


struct elemento
{
    int chave;
    char vet[100][4];
    ponteiro prox;
};



main()
{
ponteiro p,prim,h,q;
int i;

prim=NULL;
p=(ponteiro) malloc(4*sizeof(struct elemento));
h=p;
(*p).chave=1;
*(*p).vet[1]="Ana";
*(*p).vet[2]="Bia";
*(*p).vet[3]="Lia";
printf("%s\n",*(*p).vet[1]);
printf("%s\n",*(*p).vet[2]);
printf("%s\n",*(*p).vet[3]);


for(i=0;i<3;i++)
{
   q=(ponteiro)malloc(sizeof(struct elemento));
   *(*q).vet[1]=*(*p).vet[1]+*(*p).vet[1,4-i];
   *(*q).vet[2]=*(*p).vet[2]+*(*p).vet[2,4-i];
   *(*q).vet[3]=*(*p).vet[3]+*(*p).vet[3,4-i];

   printf("%c\n",*(*q).vet[1]);
   printf("%c\n",*(*q).vet[2]);
   printf("%c\n",*(*q).vet[3]);
   p=q;
}




}
    
asked by anonymous 10.11.2018 / 00:09

1 answer

2

The used pointer notation is not correct in some places, according to the declared type. When it does:

*(*p).vet[1]="Ana";

It already has several problems, since vet is an array of strings, so vet[1] is a string, so it has * more at the beginning. However assignment of strings in C is done with strcpy and (*p). can be simplified to% with%. Using all that I mentioned this statement would be:

strcpy(p->vet[1], "Ana");

In the assignment of the pointer p-> it also has the same problem, and the declaration of the q strings is certainly reversed because it ended up declaring vet[100][4] strings of size 100 .

It ended up making the solution quite complicated even with the restriction of using pointers. If the goal is to invert an array of 3 strings using pointers, then just this is enough:

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

//função de inversão utilizando ponteiros
void inverter(char *str){
    int tam = strlen(str), i;
    for (i = 0; i < tam / 2; ++i){
        char temp = *(str + i);
        *(str + i) = *(str + tam - i - 1);
        *(str + tam - i - 1) = temp;
    }
}

int main(){
    char strings[4][100];
    strcpy(strings[0], "Ana");
    strcpy(strings[1], "Bia");
    strcpy(strings[2], "Lia");

    int i;
    for (i = 0; i < 3; ++i){
        inverter(strings[i]);
        printf("%s\n", strings[i]);
    }
    return 0;
}

See it working on Ideone

    
10.11.2018 / 02:34