Sign in to follow this  
unholymight

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this