Wat's the difference ?

+1 Smn Ard · December 6, 2014
 When execute that code :
#include <iostream>
#include<malloc.h>

using namespace std;

int main()
{
    char* Word = new char;

    cin>>Word;

    Word[0]='B';
    cout << Word << endl;
    return 0;
}


it copiles perfectly ; but when I execute the following code it does not !
#include <iostream>
#include<malloc.h>

using namespace std;

int main()
{
    char* Word = new char;

    Word ="Hello";

    Word[0]='B';
    cout << Word << endl;
    return 0;
}



 

Post a Reply

Replies

Oldest  Newest  Rating
+2 Mathias Frits Rørvik · December 6, 2014
Because you are allocating memory for 1 char. And you are not freeing any memory. And WHY do you include malloc.h? Which book are you reading?

If you are working in C++, there is NO REASON why you should use char arrays to represent string, when there is a string class built in. .
+1 Smn Ard · December 6, 2014
I was working on  C++ TP (practice work) about evaluating postfix and infix expressions
so I assingned the expression to char* and I tried to modify it in the function 
M= "((a+b)/((c-d)*e))";
VersPosteFixer(M);

 
void VersPosteFixer(char *S)
{
if(BienParentheser(S)){

Pile P; char PF[50]; 
 CreerPile(P);
int j=0;
for(int i=0;S!='\0';i++)
{
if(S== '-' || S== '*' || S== '/'|| S== '+' )   
 Empiler(P,S);
else if((S>64 &&S<91) || (S>96 &&S<123) ||(S>47 &&S<58)) 
     { PF[j] = S; j++; }
else if(S==')')
      {  PF[j]= Depiler(P); j++;  }
}
PF[j]='\0';
strcpy(S,PF);
}
else cout<<"\nEXPRESSION N'EST PAS BIEN PARENTHESEE!!!!!"<<endl;
}


NB :  I just wanted to explain what I was doing I don't demand to check my code ...
       thanks for everybody .
  • 1

C++

107,044 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator