c++ - 修改传递给函数的指针时出现 Visual Studio C++ 访问冲突

标签 c++ pointers visual-studio-2012

我想实现一个简单的函数,它获取一个字符串作为 char 指针,并在一个函数中修改该字符串。请求的函数必须为空,然后我必须修改传递到我的函数中的主字符串。我遇到了访问冲突错误并用谷歌搜索,但没有任何帮助。

我的示例代码在这里:

#include "iostream"
using namespace std;
void FindCommonStr(char*& Common,int &A)
{   
    int i=0;
    while(1)
    {
        if(Common[i]=='\0')
            break;
        i++;
    }
    cout<<"Number of Elements = "<<i<<endl;
    for (int j=0 ; j<i-1;j++)   
        Common[j]='y';      
    A=2;    
}
void main()
{
    int A=0;    
    char* Common = new char;
    Common = "Hello World!";
    cout<<"Common0 = "<< Common<<endl;
    cout<<"A0 = "<< A<<endl;
    FindCommonStr(Common,A);    
    cout<<"Common1 = "<< Common<<endl;
    cout<<"A1 = "<< A<<endl;
}

实际上问题出现在FindCommonStr函数的这一部分:

for (int j=0 ; j<i-1;j++)   
            Common[j]='y';

如果我评论这部分,一切正常,但我无法更改字符串值。我还通过将函数定义为来测试指向指针解决方案的指针:

FindCommonStr(char **Common,...

但这并没有帮助,我又遇到了违规错误。 甚至有可能做这样的事情吗?

最佳答案

当你这样做时:

Common = "Hello World!";

您正在使指针 Common 指向文字 C 风格字符串(并且顺便泄漏了您通过 new 分配的原始 char之前)。尝试修改这样的文字是无效的,因此当您将其传递给 FindCommonStr 并尝试修改它时,您会遇到访问冲突。

您应该避免使用 C 风格的字符串并使用适当的 C++ std::string 代替 - 这将避免很多问题并且更加健壮,并且更适合 C++ 编程.

您的代码的固定版本:

#include <iostream>
#include <string>

using namespace std;

static void FindCommonStr(string &Common, int &A)
{
    int i = 0;
    while (1)
    {
        if (Common[i] == '\0')
            break;
        i++;
    }
    cout << "Number of Elements = " << i << endl;
    for (int j = 0; j < i - 1; j++)
        Common[j] = 'y';
    A = 2;
}

int main()
{
    int A = 0;
    string Common = "Hello World!";
    cout << "Common0 = " << Common << endl;
    cout << "A0 = " << A << endl;
    FindCommonStr(Common, A);
    cout << "Common1 = " << Common<<endl;
    cout << "A1 = " << A << endl;
    return 0;
}

或者,如果这是一项家庭作业,您出于某些深不可测的原因需要使用 C 字符串,那么仅使用 char * 字符串的固定版本可能如下所示:

#include <iostream>

using namespace std;

static void FindCommonStr(char *Common, int &A)
{
    int i = 0;
    while (1)
    {
        if (Common[i] == '\0')
            break;
        i++;
    }
    cout << "Number of Elements = " << i << endl;
    for (int j = 0; j < i - 1; j++)
        Common[j] = 'y';
    A = 2;
}

int main()
{
    int A = 0;
    char Common[] = "Hello World!";
    cout << "Common0 = " << Common << endl;
    cout << "A0 = " << A << endl;
    FindCommonStr(Common, A);
    cout << "Common1 = " << Common<<endl;
    cout << "A1 = " << A << endl;
    return 0;
}

关于c++ - 修改传递给函数的指针时出现 Visual Studio C++ 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30799172/

相关文章:

c++ - 在 boost::asio 中,为什么没有用于读/写的套接字成员函数?

c++ - C/C++ 结构中字段的顺序

c++ - 指针与引用

c++ - 在命令行参数中,为什么不能使用字符串* arr代替char ** arr

c++ - 为什么我不能在 visual studio 2012 的调试配置中将平台设置为 x64

c++ - 即使有包含保护,链接器也会提示多重定义

c++ - 你如何让 python 识别读取预编译的共享文件?

c++ - 比较处理 int 和 std::vector::size_type

asp.net-mvc-4 - 单击发布时出错 | "Object reference not set to an instance of an object"

vb.net - 将数据集 (.xsd) 分配给现有报表 (.rdlc)