Using void*

This is a discussion on Using void* within the C++ Programming forums, part of the General Programming Boards category; I'm trying to run the following code but it's not compiling. What am I doing wrong? Code: void func(void* ptr) ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    3

    Question Using void*

    I'm trying to run the following code but it's not compiling. What am I doing wrong?

    Code:
    void func(void* ptr)
    {
    	static_cast<char*>(ptr);
    	cout << ptr[0];
    }

  2. #2
    Bond sunnypalsingh's Avatar
    Join Date
    Oct 2005
    Posts
    162
    Try This...this will compile...but at runtime it will most probably fail..because trying to access uninitialised ptr
    Code:
    void *ptr;
    	char *p;
    	p=static_cast<char*>(ptr);
    	cout << p[0];

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    3

    Smile

    Thanks. Your post pointed out my problem. Here is the code:

    Code:
     void func(void* ptr, int numbytes, char value)
    {
    static_cast<char*>(ptr);
    cout << static_cast<char*>(ptr)[i];
    }

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    There is no need for the first line in your function. A static_cast (or any other cast) doesn't modify the variable you pass to it, it returns the casted variable. So to get it to work, you need to save the return value like sunnypalsingh did, or use the return value like the second line in your function does. If you do neither, the cast has no effect, which is why your first line is useless.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    3

    Red face

    Quote Originally Posted by Daved
    There is no need for the first line in your function. A static_cast (or any other cast) doesn't modify the variable you pass to it, it returns the casted variable. So to get it to work, you need to save the return value like sunnypalsingh did, or use the return value like the second line in your function does. If you do neither, the cast has no effect, which is why your first line is useless.
    Oops. My mistake. Thanks for pointing that out. I had that in there for testing purposes and forgot to take it out.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21