Thread: Malloc strings?

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174

    Malloc strings?

    I have an array of strings, and I just want to malloc room for my first string which is messages[0] and store hello world in it. This is what I have, which is failing to compile because of the malloc line. I've tried many different things but they're all swings in the dark, so could anyone please lend me a hand?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MESSAGE_SIZE 100
    
    typedef char playerMessage[MESSAGE_SIZE];
    
    int main(void) {
    	playerMessage messages[] = {};
    	char *s = "hello world";
    	
    	messages[0] = malloc(sizeof(playerMessage));
    	
    	printf("%s\n", messages[0]);
    	
        return 0;	
    }

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Get a paper and draw what you want.

    Let me make an example, but without the typedef, which in my opinion is not helping.

    You need to allocate space, equal to the length of the string, plus one for the null terminator of strings!

    Code:
    sizeof(strlen(s)+1)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    #define MESSAGE_SIZE 100
     
    int main(void) {
        
        /* Declare an array of char pointers.
           MESSAGE_SIZE is the number of these pointers.
           Every pointer is to point to a string.
         */
        char* messages[MESSAGE_SIZE];
        
        char *s = "hello world";
        
        /* Make the first pointer of the array, to point
           to 's'.
         */
        
        /* First, you need to make room for the string, 
           plus the null terminator.                     
         */
        messages[0] = malloc(sizeof(strlen(s)+1));
         
        /* Now copy the content of 's' to the array (at position 0). */
        strcpy(messages[0], s);
        
        printf("%s\n", messages[0]);
         
        return 0;   
    }
    Or, if you are sure that 's' will be in scope as long as your program executes, you can simply make the pointer to point to s, like this
    Code:
    messages[0] = s;
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > messages[0] = malloc(sizeof(strlen(s)+1));
    Now, do you know what sizeof is going to tell you about the return result of strlen() ?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Damn, missed that. Sorry guys!
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  5. #5
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Code:
    typedef char playerMessage[MESSAGE_SIZE];
    Probably the most confusing typedef I've seen in my entire life.

  6. #6
    11DE784A SirPrattlepod's Avatar
    Join Date
    Aug 2013
    Posts
    485
    Quote Originally Posted by cyberfish View Post
    Code:
    typedef char playerMessage[MESSAGE_SIZE];
    Probably the most confusing typedef I've seen in my entire life.
    I agree. Dracula probably wrote it.

  7. #7
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    std10093, I tried what you had posted, but I'm still getting the same error message at the malloc line:
    incompatible types when assigning to type ‘playerMessage’ from type ‘void *’
    Salem, I guess I don't need the sizeof function because strlen returns the size of the string, so we basically already have an integer, right?

    And as for the typedef, the way it's set out in my assignment (which actually has to do with dracula ) is the typedef is stored away in a .h file that we aren't allowed to alter, so I need to work with it.

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Mentallic
    I'm still getting the same error message at the malloc line
    Are you compiling this with a C or C++ compiler? If the latter, it's because C++ doesn't allow implicit casts...

    Quote Originally Posted by Mentallic
    I guess I don't need the sizeof function because strlen returns the size of the string, so we basically already have an integer, right?.
    You don't need it because it's complete nonsense. Consider this: sizeof(strlen(s)+1) == sizeof(0).

    ****
    EDIT: Post your current code. The error message could be related to the typedef...
    Last edited by Sebastiani; 10-07-2013 at 12:10 AM.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  9. #9
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    Quote Originally Posted by Sebastiani View Post
    Are you compiling this with a C or C++ compiler? If the latter, it's because C++ doesn't allow implicit casts...
    I'm unsure to be honest. I'm working on the terminal that comes with ubuntu and I'm using gcc with no flags to compile the file.

    Quote Originally Posted by Sebastiani View Post
    You don't need it because it's complete nonsense. Consider this: sizeof(strlen(s)+1) == sizeof(0).

    ****
    EDIT: Post your current code. The error message could be related to the typedef...
    My current code isn't the issue (at least it shouldn't be). I'm just trying to figure out how I would insert the string s into an array of strings messages[] so that I can continue with my assignment.

    In my assignment, I have a test file that has the messages array and a string. It passes messages and the string into a function. In that function, I determine what the round is in the game that's being played, and so I need to insert the string into messages[round] so that I can refer back to it in the future.

  10. #10
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Why not just use strcpy?

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Mentallic View Post
    My current code isn't the issue (at least it shouldn't be).
    If your code wasn't the issue, it'd compile.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    Quote Originally Posted by MutantJohn View Post
    Why not just use strcpy?
    Does the array have room? The messages[] that doesn't actually have a size associated with it at compile time is confusing me. How much room is there? Can I put as many strings in as I want?

    Quote Originally Posted by Sebastiani View Post
    If your code wasn't the issue, it'd compile.
    Sorry, I thought you were referring to my assignment files, not this code. What I currently have is what std10093 posted in post #2.

  13. #13
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    First, give messages a size. I am assuming what you are using is a 2d char array where each element of messages is playerMessage and as such already has a size.

    If that is the case, just strcpy into an element of messages.

  14. #14
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Mentallic View Post
    What I currently have is what std10093 posted in post #2.
    Dandy, then it should compile just fine.

    Quote Originally Posted by Mentallic View Post
    The messages[] that doesn't actually have a size associated with it at compile time is confusing me.
    Sure it does. You've declared it as MESSAGE_SIZE, right?
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  15. #15
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    Quote Originally Posted by MutantJohn View Post
    First, give messages a size. I am assuming what you are using is a 2d char array where each element of messages is playerMessage and as such already has a size.

    If that is the case, just strcpy into an element of messages.
    But I don't know how many strings I'll need to put into messages. If I make it messages[n] then I'm set on having only up to n strings, but may need more.


    Quote Originally Posted by Sebastiani View Post
    Dandy, then it should compile just fine.
    But my assignment has a .h file that the c file has included, and it has playerMessage defined as
    typedef char playerMessage[MESSAGE_SIZE];

    so I need to incorporate that into the code somehow, don't I?



    Quote Originally Posted by Sebastiani View Post
    Sure it does. You've declared it as MESSAGE_SIZE, right?
    playerMessage[MESSAGE_SIZE] is each string, but I have to store all of the strings in messages[].

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner: malloc and array of strings
    By 0ooo0 in forum C Programming
    Replies: 6
    Last Post: 03-18-2013, 08:19 AM
  2. Quick question on malloc and strings
    By officedog in forum C Programming
    Replies: 20
    Last Post: 11-06-2008, 05:14 PM
  3. how to use malloc for array of strings
    By SoFarAway in forum C Programming
    Replies: 3
    Last Post: 02-18-2005, 04:19 PM
  4. malloc() strings VS array strings
    By Kleid-0 in forum C Programming
    Replies: 5
    Last Post: 01-10-2005, 10:26 PM
  5. malloc with arrays of strings
    By Lib in forum C Programming
    Replies: 2
    Last Post: 08-03-2003, 10:46 PM