Parker
Parker

Reputation: 3

Getting a segmentation fault 11 for swap function

I'm creating a swap (using couts to test it before implement it in my actual program) function with pointers and I'm not entirely sure why I'm getting this segmentation fault when I run it. Any ideas?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

char * initializeWord(int length);
void swap(char *a, char *b);
//void scrambleWord(char *word, int size);

int main()
{
    int length;
    char *word, *x, *y;
    cout << endl << "Welcome to Word Scrambler!" << endl << endl;
    cout << "How many letters will your word have?" << endl << endl;
    cin >> length;
    getchar();
    cout << endl << "Please input a word that contains " << length << " many characters." << endl << endl;
    word = initializeWord(length);
    cout << endl;
    cout << "The word you entered was: " << word << endl << endl;
    swap(x,y);

    delete[] word;
    return 0;
}

char * initializeWord(int length)
{
    //initialization of char array
    char *cArray = new char[length];
    //user's word
    cin >> cArray;
    getchar();

    return cArray;
    delete[] cArray;
}

void swap(char *a, char *b) 
{
    cout << "First values:" << endl << a << endl << b << endl;
    char *temp = a;
    a = b;
    b = temp;
    cout << "Second values:" << endl << a << endl << b << endl;
}

Upvotes: 0

Views: 246

Answers (1)

JGroven
JGroven

Reputation: 613

cin >> cArray; This line is setting the users input as the address of your array.

You probably want:

char* initializeWord(int length)
{
   char* cArray = new char[length];

   for(int i = 0; i < length; ++i)
   {
        cin >> cArray[i]
   }
   ...
}

Or just use strings.

Upvotes: 2

Related Questions