3

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));
        }
Howard
  • 143
  • 1
  • 1
  • 12

1 Answers1

3

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.

knittl
  • 246,190
  • 53
  • 318
  • 364