Search code examples
arrayscpointerscasting

how to extract specific range of characters from string with casting to array type-- What it can't be done?


I have this code

char *c="hello";
char *x=malloc(sizeof(char)*5+1);
memcpy(x,(char[2])c,sizeof("hello")+1);
x[5]='\0';
printf("%s\n",x);

it gives error that cast specifies array type. why is that? what's the reason behind this error. Does this mean I can't cast like with array type meaning:I can cast to pointer like (char *) but I can't cast to array type like (char[2]) or (char[]) Am I missing anything?

What I need to do in my code to resolve the error cast specified array type error at

 10 |         memcpy(x,(char[2])c,sizeof("hello")+1);

Solution

  • Arrays do not have the assignment operator. You may not write for example

    char *c="hello";
    
    char s[6];
    
    s = c;
    

    As a result such a casting like

    ( char[6] )c
    

    is not allowed.