I don't think i clearly understand ur issue!. But i see an issue here. You are using(or rather reusing) the variable 'i' in the loop.
for(i=0;i<tmp;i++) <<< Here u are using the same variable 'i' as the outer loop.
// You could use a new variable like 'inner_i' here. I guess thats what u actually intended to..