【发布时间】:2017-03-01 01:17:34
【问题描述】:
我正在创建一个带有指针的交换(在我的实际程序中实现它之前使用 couts 对其进行测试)函数,我不完全确定为什么我在运行它时会遇到这个分段错误。有什么想法吗?
#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;
}
【问题讨论】:
-
你永远不会将
x和y设置为任何东西...... -
不要用 C++ 编写 C 代码。使用参考和
std::vector。 -
在你
return之后你不能delete;回来后什么都做不了 -
char *cArray = new char[length];这个语句在 C++ 中是非法的,你不能用非常量变量定义数组的大小 -
@OnurA.,动态分配数组的大小可以在运行时决定。您正在考虑自动数组,但事实并非如此。请看this
标签: c++ pointers memory-management