By analyzing your code, you made a mistake on account of references lost and pointers. Explain:
When you pass a variable to the function, you will pass a copy of the value and not the variable itself. Every change, therefore, is within the scope of that new variable - which is the function. So, if you don’t return the values, you lose them. This is why there are pointers and references!
If you pass variable address which it wishes to modify (by means of &
), you changes the variable and no longer a copy. Then it is stored in a pointer and not in a common variable. Simple example:
#include <stdio.h>
void mudando_x(int *referencia){
*referencia = 2;
}
int main (void) {
int x = 1;
mudando_x( &x );
printf("O valor de X é %d", x);
return 0;
}
The result of this is
$ O valor de X é 2
Already to struct
, instead of using the .
and the *
, you use ->
in place of .
and forgets the *
access. In setting the function you will always use the *
. Example:
#include <stdio.h>
struct estrutura {
int id;
};
typedef struct estrutura Estrutura;
void mudando_x(Estrutura *referencia){
referencia->id = 2;
}
int main (void) {
Estrutura x;
x.id = 1;
mudando_x( &x );
printf("O valor de X é %d", x.id);
return 0;
}
The result of this is
$ O valor de X é 2
So you need to do some modifications. And if it was not very clear the explanation above, you will understand better with your tidy code. See:
#include <stdio.h>
struct vet{
int tam;
int key[10];
char content[10][60];
};
typedef struct vet vetor;
void insert(vetor *s, int ind, char cnt[]){
int i;
s->key[s->tam] = ind;
for(i = 0; i < 60; i++){
s->content[s->tam][i] = cnt[i];
if (cnt[i] == '\0') break;
}
s->tam++;
}
int search(vetor *s, int ind){
int i;
printf( "search - ind: %d\n", ind );
printf( "search - s.tam: %d\n", s->tam );
for(i = 0; i < s->tam; i++) {
printf( "search - i: %d\n", i );
printf( "search - s.key[i]: %d\n", s->key[i] );
if (s->key[i] == ind)
return 1;
}
return 0;
}
int main(){
vetor s1;
s1.tam = 0;
insert(&s1, 11, "acre");
if (search(&s1, 11)) printf("found\n");
else printf("not found\n");
return 0;
}