My problem is that the dynamically allocated array only prints correctly within the function read_array. I can't figure out where I'm going wrong.
This is the output:Code:#include <stdlib.h> #include <stdio.h> #define MAX_SIZE 1000 int read_array(int *array,int size); int main (void) { int size; int *array; size = read_array(array, size); printf("\n"); for (int i = 0; i < size; i++) printf("%d ", *(array+i)); return 0; } int read_array(int *array,int size) { #define FLUSH while (getchar() != '\n') array = (int*)calloc(MAX_SIZE, sizeof(int)); printf("You may enter up to 1000 integers.\n" "How many would you like to enter?\n"); while (scanf("%d", &size)!= 1) { FLUSH; printf("Invalid number. Try again."); } if (size > 1000) size = 1000; array = (int*)realloc(array, (size - 1) * sizeof(int)); printf("Enter your numbers: \n"); for (int i = 0; i < size; i++) scanf("%d", array[i]); for (int i = 0; i < size; i++) printf("%d ", array[i]); return size; }
You may enter up to 1000 integers.
How many would you like to enter?
4
Enter your numbers:
1 2 3 4
1 2 3 4
2968 1 0 0
Why am I getting 2968 1 0 0 instead of 1 2 3 4?
The only reason I can think of is that you need a pointer to get dynamically allocated data, but "array" is a pointer. So wheres the problem?



LinkBack URL
About LinkBacks



