# Don't know why my C code is wrong with 6?

• int min(int a, int b){
return a < b ? a : b;
}

int nthUglyNumber(int n) {
int k = (int)malloc(sizeof(int) * n);
k[0] = 1;
if(n == 1){
return 1;
}
int index2 = 0, index3 = 0, index5 = 0;
int i = 0;

``````for(; i < n; i ++){
k[i + 1] = min(min(k[index2] * 2, k[index3] * 3), k[index5] * 5);
if(k[i + 1] == k[index2] * 2){
index2 ++;
}
if(k[i + 1] == k[index3] * 3){
index3 ++;
}
if(k[i + 1] == k[index5] * 5){
index5 ++;
}
}
return k[n - 1];
``````

}

• because of array out of range when i=n-1,k[i+1]=k[n].
int k = (int)malloc(sizeof(int) * n) should be int *k = (int *)malloc(sizeof(int) * n)

• Thank you~ Actually it I did code int *k = (int *)malloc(sizeof(int) * n), maybe * can't be typed into the content... However, still RUNTIME ERROR...

• you malloc n*sizeof(int ) bytes for array k.The range of k is k[0]-k[n-1].So In the for loop, when i=n-1,k[i+1]=k[n].k[n] is out of range.so you get RUNTIME ERROR.you can init i=1,and change k[i+1] to k[i] in the for loop,you will get accept.Sorry for my poor English

• Oh, I understand now... Thank you so much for your patience response and help!! By the way, I don't think your English is poor, it's easy to understand your words. Thank you again!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.