I'm trying to convert an int to char with sprintf.
for(int i=0; i<n; i++){
char buffer[100];
load = group[i];
int num = pow(10, (load-1));
for(int j=(load-2); j>=0; j--){
num+=pow(10, j);
}
sprintf(buffer,"%d",num);
(...)
When I print buffer, everything seems alright, as I just want it to be a string there.
Then, I want to store it inside an array. Specifically here:
typedef struct Unario {
char * bits ;
} Unario ;
But when trying to store buffer inside the next index of the array, all the rest of the variables saved before, update to the new buffer definition.
Here's the full function:
Unario * comprimir_en_unario ( int n, int * grupo ){
int load;
int j = 0;
int SIZE = n*2;
Unario * comprimiendo = malloc(SIZE * sizeof(comprimiendo));
for(int i=0; i<n; i++){
char buffer[100];
load = grupo[i];
printf("\ngrupo[%d] = %d\n", i, load);
int num = pow(10, (load-1));
for(int j=(load-2); j>=0; j--){
num+=pow(10, j);
}
sprintf(buffer,"%d",num);
comprimiendo[j].bits = buffer;
j++;
comprimiendo[j].bits = "0";
j++;
}
for(int i=0; i<SIZE; i++){
printf("in %d = %s\n", i, comprimiendo[i].bits);
}
return comprimiendo;
};
With the following input:
int m[6] = {8,2,8,8,2,3};
and following unwanted output:
in 0 = 111
in 1 = 0
in 2 = 111
in 3 = 0
in 4 = 111
in 5 = 0
in 6 = 111
in 7 = 0
in 8 = 111
in 9 = 0
in 10 = 111
in 11 = 0
and the one I'm trying to get:
in 0 = 11111111
in 1 = 0
in 2 = 11
in 3 = 0
in 4 = 11111111
in 5 = 0
in 6 = 11111111
in 7 = 0
in 8 = 11
in 9 = 0
in 10 = 111
in 11 = 0
Side note: I can't change the struct nor delete it because its a part of a group of structs.
mainand all#includedirectives. This also allows other people to easily test your program, by using copy&paste