Hello,
I am a C newbie working on a program using malloc and realloc functions. The problem is after compiling and running the program, the output of the array is garbage values. I would really appreciate it if someone could point out what's wrong with my code. Thanks a lot.
JustinCode:#include <iostream> using std::cout; using std::cin; using std::endl; #include <cstdlib> // for malloc and realloc memory functions int main() { int *listPtr; // pointer to dynamically allocated array int temp_input; // value which will be copied into listPtr array int count=0; // count value used to reallocate a new size for the integer // array on each integer input listPtr = (int *) malloc(2 * sizeof(int)); // allocate memory locations for a minimum of 2 integers do { ++count; cout << "Enter integer " << count << ": "; cin >> temp_input; listPtr = (int *) realloc(listPtr, count); // reallocate the array increasing its size by 1 since // one more integer is entered each time if (temp_input != -1) { *(listPtr + (count-1)) = temp_input; // count-1 so first space is used up } // assign subsequent integer into next free array spot // make sure an array is pointing to the next free spot since realloc() // function points to beginning of the array each time } while (temp_input != -1); for (int a=0; a < count; a++) { // output the dynamically allocated array cout << *(listPtr + a) << ' '; } cout << endl; return 0; }



LinkBack URL
About LinkBacks


