Why is this C for-loop not working properly? -
int main() { int t, i; int *nums; scanf("%d", &t); nums = malloc(t * sizeof(int)); for(i = 0; < t; i++) { scanf("%d", &nums[i]); } printf("hey"); }
for reason, hangs, waiting more input! ideas?
this code correct, except fact you're not freeing memory (not big issue simple code) , you're not checking scanf
errors, may cause of problem.
a better implementation error checking , correct memory handling described below:
#include <stdio.h> #include <stdlib.h> int main() { int t, i, ret; int *nums; ret = scanf("%d", &t); if(ret != 1) { /* wrong */ } nums = malloc(t * sizeof(int)); if(nums==null) { /* memory error */ } for(i = 0; < t; i++) { ret = scanf("%d", &nums[i]); if(ret != 1) { /* wrong */ } } free(nums); printf("hey"); return 0; }
Comments
Post a Comment