Results 1 to 5 of 5

Thread: Incompatible pointer type

  1. #1
    Join Date
    Dec 2007
    Beans
    9

    Incompatible pointer type

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    	
    
    int main (int argc, char *argv[]) {
    	char **pointer,*p;
    	int i = 0;
    	pointer = malloc(9);
    	while (i <= 8) {
    		pointer[i] = malloc(31);
    		pointer[i] = "hello";
    		i++;
    	}
    	 printf("%s\n",pointer[0]);
    	 pointer = realloc(pointer,30);
    	 while (i <= 19) {
    		 pointer[i] = malloc(31);
    		 pointer[i] = "hellllllooo";
    		 i++;
    	 }
    }
    The output message is a memory dump. I am compiling using gcc and the command $ gcc test.c. Thanks!

  2. #2
    Join Date
    Nov 2005
    Location
    Bordeaux, France
    Beans
    11,294
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Incompatible pointer type

    Replace

    Code:
            pointer = malloc(9);
    with

    Code:
            pointer = malloc(9*sizeof(char*));
    Or better yet:

    Code:
            pointer = calloc(9, sizeof(char*));
    「明後日の夕方には帰ってるからね。」


  3. #3
    Join Date
    Dec 2007
    Beans
    9

    Re: Incompatible pointer type

    Quote Originally Posted by HymnToLife View Post
    Replace

    Code:
            pointer = malloc(9);
    with

    Code:
            pointer = malloc(9*sizeof(char*));
    Or better yet:

    Code:
            pointer = calloc(9, sizeof(char*));
    Hi, thanks. Could you kindly explain the significant of using the sizeof of a char pointer?

  4. #4
    Join Date
    Nov 2005
    Location
    Bordeaux, France
    Beans
    11,294
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Incompatible pointer type

    Code:
    firas@nobue ~ % cat test.c
    #include <stdio.h>
    
    int main(void)
    {
            printf("%lu\n", sizeof(char*));
            return 0;
    }
    firas@nobue ~ % cc -o test test.c
    firas@nobue ~ % ./test
    8
    The size of a char* is thus 8 bytes. Therefore, if you do pointer = malloc(9), pointer will not be allocated enough memory to hold all the data you will put in it.
    「明後日の夕方には帰ってるからね。」


  5. #5
    Join Date
    Dec 2007
    Beans
    9

    Re: Incompatible pointer type

    Quote Originally Posted by HymnToLife View Post
    Code:
    firas@nobue ~ % cat test.c
    #include <stdio.h>
    
    int main(void)
    {
            printf("%lu\n", sizeof(char*));
            return 0;
    }
    firas@nobue ~ % cc -o test test.c
    firas@nobue ~ % ./test
    8
    The size of a char* is thus 8 bytes. Therefore, if you do pointer = malloc(9), pointer will not be allocated enough memory to hold all the data you will put in it.
    Thanks!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •