[英]Code giving runtime error?
i am trying to solve leetcode question :-
https://leetcode.com/problems/largest-number/ Given a list of non negative integers, arrange them such that they form the largest number. https://leetcode.com/problems/largest-number/给定一个非负整数列表,将它们排列成最大的数。
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. i am trying to sort strings by defining comparator to compare strings by concatinating right-to-left or left-to-right.例如,给定 [3, 30, 34, 5, 9],最大的形成数是 9534330。我试图通过定义比较器来对字符串进行排序,以通过从右到左或从左到右连接来比较字符串。
The program is giving runtime error.程序给出运行时错误。 Please help....
请帮忙....
int comp(const void* a, const void* b){
int p = *((int *)a);
int q = *((int *)b);
int size = 14;
char * first = (char *)malloc(size * sizeof(char));
char * second = (char *)malloc(size * sizeof(char));
first[0] = "\0";
second[0] = "\0";
sprintf(first, "%d",p);
sprintf(first, "%d",q);
sprintf(second, "%d",q);
sprintf(second, "%d",p);
return -1*strcmp(first, second);
}
char* largestNumber(int* nums, int numsSize) {
if(numsSize <=0)
return NULL;
qsort(nums, numsSize, sizeof(int), comp);
char * result = (char*)malloc(numsSize *5*sizeof(char));
int i;
for(i=0; i<numsSize; i++)
result = strcat(result, nums[i]);
return result;
}
malloc()
and throwing it away is a bad practice.malloc()
分配内存并将其丢弃是一种不好的做法。 Since you always allocate fixed amount of memory in comp
, use regular array.comp
分配固定数量的内存,因此请使用常规数组。first[0] = "\\0";
first[0] = "\\0";
, which is assigning an pointer to char
variable. char
变量的指针。 Also remove useless sprintf
, whose result is soon be overwritten.sprintf
,其结果很快就会被覆盖。int
has 4 bytes.int
有 4 个字节,则为每个元素分配 5 个字节可能太小了。 Allocate more memory.result
before passing it to strcat()
.result
指向的缓冲区传递给strcat()
之前对其进行初始化。strcat()
.strcat()
之前将其转换为字符串。malloc()
in C .malloc()
的结果。 Possible fix (not tested):可能的修复(未测试):
int comp(const void* a, const void* b){
int p = *((int *)a);
int q = *((int *)b);
char first[14];
char second[14];
sprintf(first, "%d", q);
sprintf(second, "%d", p);
return -1 * strcmp(first, second);
}
char* largestNumber(int* nums, int numsSize) {
if(numsSize <= 0)
return NULL;
qsort(nums, numsSize, sizeof(int), comp);
char * result = malloc(numsSize * 14 * sizeof(char));
int i;
result[0] = '\0';
for(i = 0; i < numsSize; i++) {
char num[14];
sprintf(num, "%d", nums[i]);
result = strcat(result, num);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.