I am trying to solve leetcode 506. (Relative Ranks problem). This is the c code not complete yet,and there's a puzzle that output is unexpected.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0,j,nums[]={5,4,3,2,1},tmp;
char str[21];
char **ret=(char **)malloc(sizeof(*ret)*5);
for(i=0;i<5;i++) //bubble sort
{
for(j=5-1;j>i;j--)
{
if(nums[i]>nums[j])
{
tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
}
for(i=0;i<5;i++)
{
if(i<3)
{
if(i==0)
*(ret+i)="Gold Medal";
else if(i==1)
*(ret+i)="Silver Medal";
else
*(ret+i)="Bronze Medal";
}
else
{
sprintf(str,"%d",nums[i]);
*(ret+i)=str;
//printf("%s ",*(ret+i));
}
}
for(i=0;i<5;i++)
printf("%s ",*(ret+i));
}
I think the output should be:
Gold Medal
Silver Medal
Bronze Medal
4
5
but the actual output is:
Gold Medal
Silver Medal
Bronze Medal
5
5
ans:
else
{
char *str=malloc(sizeof(char)*10);
sprintf(str,"%d",nums[i]);
*(ret+i)=str;
//printf("%s ",*(ret+i));
}
You are assigning str twice in your first loop. ret[3] and ret[4] both point to the same memory address. When you output your array, in your second loop, you will therefore get 5 twice, because its value is overwritten in the previous loop.
The statement *(ret+i) = str; does not copy the value of the variable str, but simply points ret+1 to the address of str. The address of str does not change when using sprintf to assign values to its bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With