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));
}