[英]How to change date that char value in C++?
我是C ++编程的初学者。
主题具有“更改的char值”。 但! 我的代码总是调用调试错误...。怎么回事.... :(
例
int main(){
char c[] = "hey";
char d[] = "hellow";
cout <<"befor/"<< c << "," << d << endl;
f(c, d);
cout <<"after/"<< c << "," << d << endl;
save();
}
void f(char* p, char* q) {
int x = *(char*)p;
int y = *(char*)q;
int temp= x;
y= x;
y = temp;
}
我想获得这个价值
以前,嘿,海洛
在/之后,嘿
我假设您想交换两个字符串,但这是行不通的,我将尝试解释原因。
int main(){
char c[] = "hey";
char d[] = "hellow";
cout << c << "," << d << endl;
f(c, d);
cout << c << "," << d << endl;
save();
}
void f(char* p, char* q) {
// When you pass the two strings to this function the arrays turn into
// pointers to the string.
int x = *(char*)p; // You now say you want x to be equal to the first
// letter of what p points to, which is "hey".
// So now x equals 'h', although its value is as
// an int.
int y = *(char*)q; // Here you assign the first letter of "hellow"
// to y. y now equals 'h' also
int temp= x; // temp now equals 'h'
y = x; // y now equals 'h' also
y = temp; // y now equals 'h' also
// Basically this whole thing does nothing.
}
通过执行此操作,可以使函数交换指针,尽管可能有太多内容无法解释。
#include <iostream>
using namespace std;
void f(char** p, char** q);
int main() {
char* c = "hey";
char* d = "hellow";
cout << "befor/" << c << "," << d << endl;
f(&c, &d);
cout << "after/" << c << "," << d << endl;
}
void f(char** p, char** q) {
char* temp = *p;
*p = *q;
*q = temp;
}
为什么必须将函数参数用作指向指针的指针或指向指针的引用,因为仅指针会给函数一个副本,而副本不足以更改原始指针。 抱歉,如果所有这些都没有道理,则您的代码有很多错误,我无法真正解释所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.