1

char* が指す文字列内のすべての文字を交換する非常に単純なテスト プログラムを作成しています。しかし、Visual C++ から非常に奇妙な例外が発生しました。

私のコードは下に貼り付けられ、Chapter1 はプロジェクトの名前です。

事前に皆様に感謝します。さらに質問がある場合は、お気軽に以下に投稿してください。

Question2.h

#ifndef _QUESTION2_H_
#define _QUESTION2_H_

namespace Q2
{
    void swap(char *begin, char *end);

    void reverse(char *str);

    void run();
}

#endif

Question2.cpp

#include <iostream>

#include "Question2.h"

using namespace std;

namespace Q2
{
void swap(char *begin, char *end)
{
    char tmp = *begin;
    *begin = *end;
    *end = tmp;
}

void reverse(char *str)
{
    char *begin = str;
    char *end = str;

        while(*end != NULL)
        end++;
    end--;

        for(; begin < end; begin++, end--)
        swap(begin, end);
}

void run()
{
    char *str1 = "hello";

    reverse(str1);

    cout << str1 << endl;

    return;
    }
}

main.cpp

#include <iostream>

#include "Question2.h"

int main()
{
    Q2::run();

    return 0;
}
4

2 に答える 2

0

以下を使用すると、はるかに簡単で安全で読みやすくなりstd::stringます。

#include <string>

void swap(std::string& str, int index1, int index2) {

    char temp = str[index1];
    str[index1] = str[index2];
    str[index2] = temp;

}

void reverse(std::string& str) {

    for (int i = 0; i < str.size() / 2; i++)
        swap(str, i, str.size() - i - 1);

}
于 2013-09-05T22:30:40.077 に答える