[英]Reversing an array of characters in C++ using pointers
因此,該程序應該使用循環來計算包含“ 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;
}
}
好,讓我們從頂部開始
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);
這將返回一個長度計數。 假設字符串為“ abc”,計數為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--;
}
}
免責聲明-我尚未測試此代碼。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.