Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

locus

Having problems with malloc

This topic is 5855 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

I'm using the book 'Teach Yourself C in 24 Hours' and in the chapter about allocating memory, I keep getting the error "cannot convert 'void *' to 'char *' in function main()". Here's the code from the book:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void str_copy(char *str1, char *str2);

main()
{
   char str[] = "Allocating memory.";
   char *p_str; // pointer to string
   int result;

   p_str = malloc(strlen(str) + 1); // right here is where I get the error //
   
   if(p_str != NULL)
   {
      str_copy(str, p_str);
      printf("The string pointed to by p_str is: \n%s\n", p_str);
   result = 0;
   }
   else
   {
      printf("malloc() function failed.\n");
      result = 1;
   }
   return result;
}

void str_copy(char *str1, char *str2)
{
   int i;
   
   for(i=0; str1; i++) // there's supposed to be braces around an i after the str1, but for some reason, they aren't showing up in this post //
      str2[i] = str1[i];
   str2[i] = '\0';
}
  
It's really bugging me because I'm entering everything just as it is in the book, so I know it's not my fault, or, at least it doesn't seem to be, but I can't figure out what the problem is. Thanks to anyone who can help. [edited by - locus on September 15, 2002 2:36:13 AM]

Share this post


Link to post
Share on other sites
Advertisement
Are you trying to compile it with a c++ compiler? While the code is valid c, it isn''t valid c++. Try this:

p_str = (char*)malloc(strlen(str) + 1);

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!