Search code examples
arraysvariable-assignmentrealloc

Simple C code, with vexing "incompatible types in assignment" error


Just a simple program to get used to pointers. The program is supposed to put the contents of a portion of my memory into a character array in reverse order of how the memory is read. I.E. looking at descending memory address, and I want to store it in descending order in a character array.

My compiler keeps telling me: "error incompatible types in assignment"

On the line with the realloc function

What am I doing wrong? I seems to me that both "reverse", and the result of realloc should be pointers to type char?

My code:

int main(){
char  first[]="hello mark", strng='h', reverse[]="";
char* ptr=&first[10];
int i=0;
    while(ptr > (&strng-0xf4240)){
        printf("%c", *ptr--);
        reverse = realloc(reverse, (i++ * sizeof(char)));
        reverse[strlen(reverse)-i] = *ptr;
    }
printf("%s", reverse);
return 0;
}

Thank you!

EDIT: Sorry I mis-posted these as comments below

Thanks for the help, the first and second comment got it! I did have the required #includes, I just forgot to copy them into stack overflow. You were right, now I'm stuck on the non-null terminated strlen(). I'll solve that one on my own. Thanks again!

I spoke too soon, it compiled alright, but there is a logic error. The while loop will execute one time. However, subsequent loops still fail, regardless of the initial value of i. The line that causes the failure is the the line that calls realloc


Solution

  • You can't realloc memory that wasn't malloced in the first place. You should declare reverse as "char *" and malloc it to start with.

    This will get you going, but you really should think about reallocing in chunks, rather than one byte at a time. Oh, I didn't bother to fix the fact that "reverse" is probably not null terminated when you try the strlen - I'll leave that as an exercise for the reader.

    int main(){
    char  first[]="hello mark", strng='h';
    char* reverse;
    char* ptr=&first[10];
    reverse = (char*)malloc(1);
    reverse[0] = '\0';
    int i=0;
        while(ptr > (&strng-0xf4240)){
            printf("%c", *ptr--);
            reverse = (char*)realloc(reverse, (i++ * sizeof(char)));
            reverse[strlen(reverse)-i] = *ptr;
        }
    printf("%s", reverse);
    return 0;
    }