在功能块之后更改指针值

Change pointer value after function block

我有这个代码:

#include <iostream>
#include <string.h>
using namespace std;

void copyString(char *input, int offset, int length, bool invert, char *output, int output_offset)
{
char *cp = new char[length+1];
for (int i = 0; i < length + 1; i++)
{
    cp[i] = input[offset + i];
}
if (invert)
{
    for (int i = 0; i < length/2; i++)
    {
        swap(cp[i], cp[length - i - 1]);
    }
}
int count = 0;
while (output[count])
    count++;
int cutlength = count - output_offset;
char *temp = new char[count + 1];
for (int i = 0; i < count + 1; i++)
    temp[i] = output[i];
for (int i = 0; i < cutlength; i++)
{
    temp[output_offset + i] = cp[i];
}
output = temp;
}

void main()
{
char *st = "Hello world";
cout << "st= " << st << endl;
char *st2 = "My name is C++";
cout << "st2= " << st2 << endl;
copyString(st, 6, 5, true, st2, 11);
cout << "st2 output= " << st2 << endl;
system("Pause");
}

想法是该函数将复制输入字符串的长度并用复制的字符串替换输出的一部分。

我只想在 copyString 函数后更改 st2 值,但我似乎无法通过 temp[=20= 更改它] 变种。但是,如果我尝试更改函数中的 st2 值,则会出现访问冲突错误。知道如何解决这个问题吗?

你的copyString函数大体上类似于Cstrcpy函数(如果不把倒置选项带进去的话)。它需要输出是一个已分配的缓冲区(一个 char 数组),其大小足以将字符串内容写入其中(例如,您可以使用 new char[strlen(str) + 1] 分配一个缓冲区)。但是,您正试图写入字符串常量 "Hello world""My name is C++" 所在的内存。这显然是内存访问冲突(否则您将修改这些常量)。

不用说,这种处理字符串的方式非常容易出错,而且远不是 C++ 风格。

1) 你计算 output 长度(未定义的行为!),而不是 input 长度。

2) output 指针无处可去 - 你想为它使用引用函数参数吗?

st 和 st2 是指向常量字符串的指针,因此您不应尝试更改其中的内容(尽管您可以使它们指向完全不同的字符串)。

要使 st2 成为可编辑的字符数组(字符串),您应该按如下方式声明 st2

char st2[] = "My name is C++";

在你的 copyString 函数中,输出指针最初指向与 st2 相同的位置,然后在函数的末尾使输出指针指向不同的字符串。然而,这不会以任何方式改变 st2 或其内容。

您需要使 st2 成为一个字符数组并在 copyString 函数中编辑该数组,或者让 copyString 函数创建并 return 一个 st2 可以指向的新字符串(尽管可能最终如果你不小心,内存泄漏)。

下面应该做你想要的。可以通过完全删除 cp 并直接从输入缓冲区写入输出缓冲区来稍微改进它。

void copyString(char *input, int offset, int length, bool invert, char *output, int output_offset)
{
    char *cp = new char[length+1];
    for (int i = 0; i < length + 1; i++)
    {
        cp[i] = input[offset + i];
    }
    if (invert)
    {
        for (int i = 0; i < length/2; i++)
        {
            swap(cp[i], cp[length - i - 1]);
        }
    }
    int count = strlen(output);
    int cutlength = count - output_offset;
    for (int i = 0; i < cutlength; i++)
    {
        output[output_offset + i] = cp[i];
    }
    delete[] cp;
}

void main()
{
    char st[] = "Hello world";
    cout << "st= " << st << endl;
    char st2[] = "My name is C++";
    cout << "st2= " << st2 << endl;
    copyString(st, 6, 5, true, st2, 11);
    cout << "st2 output= " << st2 << endl;
    system("Pause");
}

内存访问冲突是由于您正在尝试修改一个字符串,该字符串的大小不能容纳额外的长度(即您的情况下的 st2)

注意:当您更新了 st2 <-- temp.

的基地址时,Temp 方法工作正常,没有错误

还建议根据偏移量和 输入参数 长度进行边界检查。 通常使用 strcpy_s 优于 strcpy.