![](/img/trans.png)
[英]I want to convert int to char array where 0-7 bits of int are 1st char 8-15 2nd etc
[英]How to pass char type array to a function and copy 1st char array to 2nd chart array and compare it using c++?
這是我想要的:
聲明一個大小為15的字符數組,以存儲用戶的字符(字符串輸入)值。 現在執行以下任務:
這是我的代碼
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
void mycopy(char array);
int main(){
//Using Loop to input an Array from user
char array[15];
int i;
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
for (i = 0; i < 15; i++)
{
cin >> array[i];
}
// output each array element's value
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
cout << setw(7) << j << setw(13) << array[j] << endl;
}
mycopy(array[15]);
return 0;
}
void mycopy(char array[15]) {
char array1[15];
strncpy_s(array1, array, 15);
cout << "The output of the copied Array" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
cout << setw(7) << j << setw(13) << array1[j] << endl;
}
}
上面的代碼將數組傳遞給函數Copy()並將第一個數組的值復制到第二個char數組,但是由於傳遞了無效參數,該代碼生成了異常。 當我搜索堆棧溢出時,但沒有找到任何類似的問題可以解決我的問題。 提前致謝。
不要使用strncpy_s
,這是非標准的。 相反,請像原來一樣使用strncpy
。 為了使用它,您需要包括cstring
。
#include <cstring>
您的原型和mycopy()
定義是不同的。 您的原型需要一個char
但是您的定義需要一個char
數組。 使它們都采用數組。 以下三個中的任何一個都將起作用:
void mycopy(char* array);
void mycopy(char array[]);
void mycopy(char array[15]);
當您在main()
中調用mycopy()
,您嘗試訪問第15個索引處的數組並將該字符傳遞給函數。 這是錯誤的,因為第15個索引超出范圍,並且該函數采用了指向char
數組而不是char
的指針。 您只需要將指針傳遞給數組即可。
mycopy(array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.