Jump to content
  • Advertisement
Sign in to follow this  
unholymight

This surprised me in ways I didn't know existed.

This topic is 3816 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Well what's the problem?!? The value displayed for each pointer is DIFFERENT!!! Why aren't they the same?? Can someone show me what I kind of drugs I am smoking and in what quantity. Thanks! *Thumbs Up*
#include <stdio.h>

int main()
{
  char* pszWord = new char[255];
  char* pszWordCopy = new char[255];
  
  while (true) {
    printf("Enter a word:");
    scanf("%s", pszWord);

    //Show the original word
    printf("\nThe Word: %s \n", pszWord);
            
    //Make a copy of the almighty Word
    *pszWordCopy = *pszWord;
    
    //Show the copy
    printf("\The Copy: %s \n", pszWordCopy);
          
    printf("\n\n");
  }
}



Share this post


Link to post
Share on other sites
Advertisement
What do you think this line does?


*pszWordCopy = *pszWord;


Both are of type char*, so applying the * operator returns the first char pointed to. It does not magically copy one string to another.


void f()
{
char *s=new char[10];
std::strcpy(s,"hello");

*s='j';

std::cout << s << "\n"; // prints "jello"
}


std::string would do exactly what you want with the = operator.

Share this post


Link to post
Share on other sites
    //Make a copy of the almighty Word
*pszWordCopy = *pszWord;


This line does not mean what you think it means. It's equivalent to "pszWordCopy[0] = pszWord[0]". Maybe you meant to do "strcpy(pszWordCopy, pszWord)"?

EDIT: or what EasilyConfused said.

Share this post


Link to post
Share on other sites
*pszWordCopy = *pszWord;
This will copy only the first char in the array, equal to:
pszWordCopy[0] = pszWord[0];

You need to use something like memcpy to copy the whole array, or better yet use std::string if you are dealing with c++ instead of plain c.

EDIT: Note to self: Always refresh the thread before posting the reply ;(

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!