使用指针反转C ++中的字符数组

时间:2017-07-19 23:49:29

标签: c++ arrays pointers c-strings

所以程序应该使用循环来计算包含" Hello World!"的字符数组的总大小,将该计数作为int返回,然后调用一个使用的函数从数组的开头和结尾开始的指针交换字符直到空点" "在两个词之间。我已经在很大程度上找到了代码,但它没有正确编译并且无法显示或无法完成交换,我不断收到以下错误: " LNK1168无法打开Lab06.exe进行写入"
我该如何解决这个问题?

#include "targetver.h"
#include <iomanip>
#include <array>
#include <stdio.h>
#include <tchar.h>
#include <string>
using namespace std;

int main()
{
    //int to hold size of array
    int count = 0;
    // declare a c-string to reverse
    char myString[] = "Hello world!";
    //print array as is
    cout << myString << endl;
    //find size of the array


    // call the reverser function
    reverser(myString, count);

    // output the result
    cout << myString << endl;

    system("PAUSE");
    return 0;
}

int findSize(char myString[], int count)
{

    count = (unsigned)strlen(myString);
    cout << "The size of the Array is: " << count << endl;
    return count;

}


void reverser(char myString[], int count)
{
    findSize(myString, count);
    char *strPtr;
    char *endPtr;
    endPtr =& myString[count];
    strPtr = myString;

    for (int x = 0; x <= count; x++)
    {
        strPtr++;
        *strPtr = myString[x];
        endPtr--;
        *endPtr = myString[count--];
        *strPtr = *endPtr;
        cout << strPtr << endl;
        cout << endPtr << endl;
    }

}

2 个答案:

答案 0 :(得分:2)

好的,让我们从顶部开始

findsize返回大小,但你忽略它。您尝试将count作为参数传递,并希望更新findsize中的count。这不是C的工作方式。所以先做

int findSize(char myString[])
{

    int count = strlen(myString);
    cout << "The size of the Array is: " << count << endl;
    return count;
}

现在当你调用findsize时,你必须记住结果。

int count = findsize(myString);

返回长度的计数。假设字符串是&#39; abc&#39;,count将是3。

该字符串有3个字符myString [0],mystring [1]和ystring [2]。请注意,没有[3]字符..

逆转到位很棘手。

void reverser(char myString[])
{
    int count = findSize(myString);
    char *strPtr = myString
    char *endPtr = &myString[count - 1];
    strPtr = myString;

    for (int x = 0; x <= count / 2; x++)
    {
       char swap = *strPtr;
       strPtr[x] = *endPtr;
       *endPtr = swap;
       endPtr--;
    }
}

免责声明 - 我尚未测试此代码。

答案 1 :(得分:0)

count = findSize(myString, count);

因为findSize返回count,所以你需要count来等于它返回的值。

void reverser(char myString[])
{
int count = findSize(myString);
char *endPtr;
endPtr =& myString[count-1];
char *temp = new char[count];

for (int x = 0; x < count; x++)
{
     temp[x] = *endPtr;//this assgins the last letter of myString to the first element of temp 
     endPtr--;//decrement so endPtr points to myString[count - 1];
}
//now transfer
for(int x = 0; x < count; x++){
    myString[x] = temp[x];
}
delete [] temp;
}