Article 6D6SY Why infinite loop for input elements, bigger than single digit.

Why infinite loop for input elements, bigger than single digit.

by
ajiten
from LinuxQuestions.org on (#6D6SY)
In the below code, want to display the elements in an array, in a format that there are two rows, and the first row is the element index; while the second row has the actual element. But, the second row elements are spaced by their size.

Issue arises of infinite loop, if the array elements are more than single digit big.

Code:#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
int *intvals = NULL; //array of integers
int **vals= NULL;//array of pointers
int total_elements;

if (isatty(fileno(stdin))) {
printf("How many elements in the array: ");
}
scanf("%d", &total_elements);

intvals = malloc(total_elements*sizeof(int));
vals = malloc(total_elements*sizeof(int *));
for(int i= 0; i<total_elements; ++i) {
vals[i]= &intvals[i];
scanf("%d", vals[i]);
}
for (int i=0; i<total_elements; ++i)
printf(" %d ", i);
printf("\n");
for (int i=0, j=0, no_of_spaces=0; i<total_elements; ++i){
//printf("%d:", i);
while((*(int *) vals[i])/10 >0) no_of_spaces++;
//printf("for %d, number of spaces : %d", *(int *) vals[i], no_of_spaces);
while(no_of_spaces)
{
printf(" ");
no_of_spaces--;
}
printf("%d", *(int *)vals[i]);
}
}
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments