Reading in an array of 12 numbers with spaces in between each number - C programming -
i new c programming student , having trouble code working on. need ask user 12 number barcode spaces in between each value. also, need refer each individual value in array later on in code. example, if array x[12], need use x[1], x[2], , other values calculate odd sum, sum, etc. below first function read in bar code using loop. assistance script of function help.
#include <stdio.h> #define array_size 12 int fill_array() { int x[array_size], i; printf("enter bar code check. separate digits space >\n"); for(i=0; i<array_size; i++){ scanf("% d", &x); } return x; }
you should pass array read argument , store read there.
also note % d invalid format specifier scanf().
#include <stdio.h> #define array_size 12 /* return 1 if suceeded, 0 if failed */ int fill_array(int* x) { int i; printf("enter bar code check. separate digits space >\n"); for(i=0; i<array_size; i++){ if(scanf("%d", &x[i]) != 1) return 0; } return 1; } int main(void) { int bar_code[array_size]; int i; if(fill_array(bar_code)) { for(i=0; i<array_size; i++) printf("%d,", bar_code[i]); putchar('\n'); } else { puts("failed read"); } return 0; } alternately, can allocate array in function , return address.
#include <stdio.h> #include <stdlib.h> #define array_size 12 /* return address of array if succeeded, null if failed */ int* fill_array(void) { int *x, i; x = malloc(sizeof(int) * array_size); if (x == null) { perror("malloc"); return null; } printf("enter bar code check. separate digits space >\n"); for(i=0; i<array_size; i++){ if(scanf("%d", &x[i]) != 1) { free(x); return null; } } return x; } int main(void) { int *bar_code; int i; if((bar_code = fill_array()) != null) { for(i=0; i<array_size; i++) printf("%d,", bar_code[i]); putchar('\n'); free(bar_code); } else { puts("failed read"); } return 0; }
Comments
Post a Comment