I am writing a program that asks the user for their first, middle, and last name, then concatenates the 3 fixed size arrays into one array that is dynamically created based on the length of the full name.
When executing the program, I get this error:
Unhandled exception at 0x1026f8e0 (msvcr90d.dll) in Lab5.exe: 0xC0000005: Access violation reading location 0x00000000.
It occurs in the DisplayName function. I noticed when I return to Main after calling my Allocate function that the ptrName shows <bad pointer> in the debug menu.
Here is the code for my 3 files:
Lab5header.h
Main.cppCode:// Function Prototype void Allocate(char [], char [], char [], char *); void DisplayName(char *);
Implementation.cppCode:// Pre-defined headers #include <iostream> #include <cstring> // User-defined headers #include "Lab5Header.h" using namespace std; const int ARRAY_SIZE = 12; int main() { // Declare fixed-sized array char firstName[ARRAY_SIZE] = ""; char middleName[ARRAY_SIZE] = ""; char lastName[ARRAY_SIZE] = ""; char *ptrName = NULL; // Variable to check whether user wants to continue program or not. char answer = 'y'; do { cout << "WARNING: First, middle, and last name can only be up to 12 characters long."; cout << endl << endl; // Get users last, first, then middle name. cout << "Please give me your last name. > "; cin >> lastName; cout << endl << "Please give me your first name. > "; cin >> firstName; cout << endl << "Please give me your middle name. > "; cin >> middleName; // Find the total length of the users full name. Then, dynamically allocate a new // array for the users full name. Allocate(lastName, firstName, middleName, ptrName); // Call function to display the full name in its correct order DisplayName(ptrName); } while (answer == 'y' || answer == 'Y'); // Delete the array we created delete [] ptrName; ptrName = NULL; system("pause"); return 0; }
I know that I need to pass the pointer by reference but all my attempts at this end up giving me more errors.Code:// Pre-defined headers #include <iostream> #include <cstring> // User-defined headers #include "Lab5Header.h" using namespace std; void Allocate(char lastName[], char firstName[], char middleName[], char *ptrName) { // Determine the length of the array int arrayLength = strlen(firstName) + strlen(middleName) + strlen(lastName) + 3; // Create new Array ptrName = new char [arrayLength]; // Copy and append First, Middle, and Last names into the new array strcpy(ptrName, firstName); strcat(ptrName, " "); strcat(ptrName, middleName); strcat(ptrName, " "); strcat(ptrName, lastName); cout << endl << ptrName << endl; return; } void DisplayName(char *ptrName) { cout << endl << endl << ptrName; return; }



LinkBack URL
About LinkBacks



