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.
CodePudding user response:
Because your the bits in your struct can not store values, it is only a pointer
So you have to make sure each time you have stored your stirng somewhere
In your used function, each time you use sprintf, the stored value in buffer will be refreshed
In that case, your final output must be the lastest value of buffer
It means, if you changed the array from { 8,2,8,8,2,3 } to { 8,2,8,8,2,4 }, the final output will be all in 1111(the lastest value of buffer)
Here is one way to save it, I used 2d array to store the string
Unario * comprimir_en_unario(int n, int * grupo)
{
int load;
int j = 0;
int SIZE = n * 2;
Unario * comprimiendo = (Unario *)malloc(SIZE * sizeof(Unario));//No need to change.
char buffer[100][100];//Use 2d array to store the string each time
for (int i = 0; i < n; i )
{
load = grupo[i];
printf("grupo[%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[i][0], "%d", num);//Related changes
comprimiendo[j].bits = &buffer[i][0];//Related changes
j ;
comprimiendo[j].bits = "0";
j ;
}
for (int i = 0; i < SIZE; i )
{
printf("in %d = %s\n", i, comprimiendo[i].bits);
}
return comprimiendo;
}
You may find more solutions after you noticed the problem of your origional function