如何在C++中更改char值的日期?

问题描述:

我是C++编程的初学者。如何在C++中更改char值的日期?

该主题有“改变了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; 


} 

我想这个值

befor /哎, hellow

后/ hellow,哎


enter image description here

+1

你能解释一下吗,你很难弄清楚你正在经历什么问题或你正在努力完成什么。很明显的是,你不高兴,但可悲的是,这不足。 –

+0

没有错误http://coliru.stacked-crooked.com/view?id=88a670352c63d925 –

+1

如果你试图交换两个字符串的值,那么你可以做'char * temp = p; p = q; q = temp;'在函数'f'中。但是,如果你更详细地解释你的问题并且更加清晰,它将会很棒:) – tkhurana96

我假设你想交换两个字符串,但这不起作用,我会试着解释为什么。

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; 
} 

为什么函数参数都被视为要么指向指针或引用指针,因为只是指针只会给功能的副本,副本不够好,改变原有的指针。对不起,如果这些都不合理,你的代码有很多错误,我不能真正解释所有的东西。

+0

为什么不使用引用 - 例如'void f(char *&p,char *&q){' –

+1

@Ed Heal Ye会避免所有的解引用,希望OP能更好地理解指针的指针,虽然我不指望它。 – Zebrafish

+0

感谢你,我第一次发现这件事。我现在需要研究'交换'。 – kimbanana