Thread: error: incompatible types when assigning to type char[ ] from type ‘char *’ , malloc(

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    40

    error: incompatible types when assigning to type char[ ] from type ‘char *’ , malloc(

    Code:
    #define BUFLEN 512
    
    int main(int argc, char **argv)
    {
      char command_string[BUFLEN];
    
            command_string=(char*)malloc(BUFLEN * sizeof(char));
            if(command_string==NULL) 
            {
              perror("malloc");
              exit(EXIT_FAILURE);
            }
    
    return 0;
    }
    reset; gcc -g -Wall -ansi -pedantic testes.c -o tt
    output:
    testes.c: In function ‘main’:
    testes.c:53:20: error: incompatible types when assigning to type ‘char[512]’ from type ‘char *’

    why i get this error and how to solve it?

  2. #2
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,859
    You command string is not a char *

    What you want is something like this:
    Code:
      char *command_string;
      command_string = malloc(BUFLEN * sizeof(command_string));
    Note that malloc is not casted, and the dependence on command_string of having (char *) is removed.
    Fact - Beethoven wrote his first symphony in C

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    40
    why i do not have to cast the malloc? i have seen many examples on the internet that are casting.
    furthermore, if i would like to keep char command_string[BUFLEN];
    then how do i allocate memory for it?

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    157
    read this : casting malloc

  5. #5
    Registered User
    Join Date
    May 2012
    Posts
    40
    @africanwizz , thank you for the usefull link, but i just explained part of my problem, btw can u give me some examples for what is explained in that page, nammely:
    ""
    There is nothing wrong with this except in the event that stdlib.h, the header which declares malloc, is not included. If the return of malloc is cast then the error which would be flagged is hidden, resulting in a difficult to find bug. Also, during maintenance, if the type of the pointer changes but the cast is not changed, once again there is a difficult to find bug.
    ""
    i would like to see some examples of what is said in those statements.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by tindala View Post
    why i do not have to cast the malloc? i have seen many examples on the internet that are casting.
    The short answer is that people who wrote those examples didn't understand what they are doing. Yes, a lot of people have done it. They were all mistakenn

    Because, if malloc() is used correctly in C, type conversion is not required. Type conversions (aka casts) are often used to cope with problems due to misusing malloc() - and they hide the problems (stop the compile complaining) without fixing them.

    The correct use of malloc() in C is simple: (1) #include <stdlib.h> first. (2) don't type convert the result.

    Most examples of C code where type conversions are used are due to forgetting <stdlib.h>. That causes the compiler to assume malloc() returns an int, so it will complain if there is no type conversion. #include <stdlib.h> is the correct fix to that complaint. A cast will shut up the compiler, but at run time the behaviour is then that malloc() returns a pointer, which is then converted to int (since that is what the compiler is forced to assume), and that int is converted back to a pointer(thanks to the typecast). Values of pointers are not guaranteed to survive the "pointer to int to pointer" round trip (an int cannot necessarily represent every value that a pointer can, or vice versa) so any code which uses the pointer then has undefined behaviour.

    Things are a little different if your C compiler is actually a C++ compiler, but casting the return of malloc() is rarely a good idea then either. A lot of people trying to write code which compiles with both C and C++ compilers will typecast malloc(). The better solution would be to configure their compiler so it compiles as C, not as C++ (since that prevents using any C++ features in code that is supposed to be pure C) or to write C++ code without using malloc() (use operator new instead).

    Quote Originally Posted by tindala View Post
    furthermore, if i would like to keep char command_string[BUFLEN];
    then how do i allocate memory for it?
    You can't.

    If you want to use "char command_string[BUFLEN]" then you need to ensure the value of BUFLEN is specified in advance (i.e. hard-coded before compiling your code).

    If you want a resizable array, define command_string as a pointer, and use malloc()/realloc()/free().

    There is no midway point between those options: they are mutually exclusive - you can't define something as an array with defined size and then allocate it using malloc(). A pointer is not an array (although it can be used like an array sometimes) and an array is not a pointer (although it can be used as a pointer sometimes.

    Incidentally, Click_here made a typo. His example should have been
    Code:
    char *command_string;
    command_string = malloc(BUFLEN * sizeof(*command_string));     /*  note the asterix in the sizeof() operation */
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User
    Join Date
    May 2012
    Posts
    40
    @grumpy thank you very much for the answer, u got me a very good answer. that clarified me a lot.
    Code:
    char *command_string;
    command_string = malloc(BUFLEN * sizeof(*command_string));
    isnt the same as
    Code:
    char *command_string;
    command_string = malloc(BUFLEN * sizeof(char));
    ??
    Last edited by tindala; 03-30-2014 at 07:10 AM.

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The first works even if the type of command_string changes (for example, to a pointer to some wide character type). The second does not.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,859
    Incidentally, Click_here made a typo. His example should have been...
    Sorry, grumpy is correct - I missed that one.

    isnt the same as...
    No - Because if I change the data type of command_string, I won't have to go through and change all the chars to this new data type.

    Consider this example which may send a pattern from a microcontroller (using stdout) with limited space (so the memory needs to be freed and and table recalculated)
    Try types char*, then unsigned char*, and then unsigned int* to fix the bug as comments note.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define DATA_SIZE1 0xFF
    #define DATA_SIZE2 0x1FF
    
    
    int main(void)
    {
        //char *myDynamicArray = NULL;
        //Bug found: Negative numbers were being printed
        //Change to "unsigned char"
    
        //unsigned char *myDynamicArray = NULL;
        //Bug found: Overflow detected on "unsigned char" type
        // Change to type unsigned int
    
        unsigned int *myDynamicArray = NULL;
    
        if( (myDynamicArray = malloc(DATA_SIZE1 * sizeof(*myDynamicArray))) != NULL)
        {
            int i = 0;
    
            for(i=0; i<DATA_SIZE1; i++)
            {
                myDynamicArray[i] = i;
                printf("%d ", myDynamicArray[i]);
            }
    
            free(myDynamicArray);
        }
        else
        {
            //Send predefined error code string
            puts("<Err=0xE101>");
        }
    
        putchar('\n');
        
        /***************************************/
        //  Here there may be lots of processing
        //
        //  Lots of memory will be needed
        //
        //  That is why myDynamicArray needs to 
        //  be freed...
        /***************************************/
            
        if( (myDynamicArray = malloc(DATA_SIZE2 * sizeof(*myDynamicArray))) != NULL)
        {
            int i = 0;
    
            for(i=0; i<DATA_SIZE2; i += 2)
            {
                myDynamicArray[i] = i;
                printf("%d ", myDynamicArray[i]);
            }
    
            free(myDynamicArray);
        }
        else
        { 
            //Send predefined error code string
            puts("<Err=0xE102>");
        }
        
        
        /***************************************/
        //  Here there may be lots of processing
        //
        //  Lots of memory will be needed
        //
        //  That is why myDynamicArray needs to 
        //  be freed...
        /***************************************/
    
        return EXIT_SUCCESS;
    }
    Fact - Beethoven wrote his first symphony in C

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    40
    @Click_here, thank you for the answer, i liked ur example to show me how that thing is properly used in some situations.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 07-24-2012, 10:41 AM
  2. Replies: 2
    Last Post: 11-23-2011, 12:30 PM
  3. Replies: 17
    Last Post: 03-06-2008, 02:32 PM
  4. error involving char type
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 05-18-2007, 05:54 PM
  5. Converting type string to type const char*
    By rusty0412 in forum C++ Programming
    Replies: 1
    Last Post: 07-11-2003, 05:59 PM

Tags for this Thread