2014-10-31 204 views
-1
int main(int argc, char *argv[]) { 
    if(argc!=3) { 
     printf("You must pass exactly three para \n"); 
     return 0; 
    } 

    char *buffer = argv[1]; 
    //printf("The length of the buffer string is %d\n",buflen); 
    char *mystring = argv[2]; 
    //printf("The length of the user string is %d\n",len); 
    addstring(buffer, mystring); 
    return 0; 
} 

int addstring(char *buffer, char *mystring) 
{ 
    int buflen = strlen(buffer); 
    int len = strlen(mystring); 
    char *dest; 
    *dest = (char *)malloc(buflen + len + 1); 
    printf("The size of destination is %lu\n",sizeof(dest)); 

    dest = strcpy(dest,buffer); 
    dest = (dest + buflen); 
    dest = strcpy(dest,mystring); 
    printf("The final string is %p",dest); 
    return 0; 
} 

在上面的代码中,函数addstring(..)鞋这个错误Assignment makes integer from a pointer without a cast。我知道我正在接受一个指针的值并将其放入整数,但我该如何解决这个错误?赋值使指针无整型指针

+3

你已经做了'* DEST =(的char *)malloc的(buflen + LEN + 1);'而不是'DEST =的malloc(buflen + LEN + 1);' – Chandru 2014-10-31 07:16:46

+0

你需要'#include '和'#include ' – 2014-10-31 08:12:27

回答

0

变化

char *dest; 
*dest = (char *)malloc(buflen + len + 1); 

char *dest; 
dest = (char *)malloc(buflen + len + 1); 

编辑:由于@POW说,你不用投malloc的结果

+2

不要施加'malloc'结果 – P0W 2014-10-31 07:18:48

+1

这与已发布的评论有何不同?如果你要发表评论作为答案,至少花时间解释你的答案背后的推理。 – 2014-10-31 07:18:53

+0

@ DavidC.Rankin我发布我的答案时没有看到评论。相同的答案可能会在几秒钟内发布。 – 2014-10-31 07:28:03

1

即使改变*destdest后,你的函数addstring是不正常工作..只需尝试像这样

int addstring(char *buffer, char *mystring) 
{ 
int buflen = strlen(buffer); 
int len = strlen(mystring); 
char *dest; 
dest = (char *)malloc(buflen + len + 1); 
printf("The size of destination is %d\n",sizeof(dest)); 

strcpy(dest,buffer); 
strcat(dest,mystring); 
printf("The final string is %s\n",dest); 
return 0; 
} 
1

你做

*dest = (char *)malloc(buflen + len + 1); 

,而不是

dest =malloc(buflen + len + 1); 

你的程序警告说,对我此行

printf("The size of destination is %lu\n",sizeof(dest)); 

sizeof()返回类型不长unsigned int类型。

因此,使用%d%u%zu作为printf()语句中的访问说明符。

+1

'sizeof'返回'size_t'类型,所以转换说明符应该是'%zu'。或者如果它不被编译器支持,那么使用显式转换'printf(“%u \ n”,(unsigned)sizeof(dest));' – user694733 2014-10-31 07:37:51

+0

感谢您的评论,我纠正了我的错误 – Chandru 2014-10-31 07:43:18

0

代码中存在多个问题。 请检查下面的代码

int addstring(char *buffer, char *mystring) 
{ 
    int buflen = strlen(buffer); 
    int len = strlen(mystring); 
    char *dest; 
    /* No need to type-cast the malloc() */ 
    dest = malloc(buflen + len + 1); /* *dest holds the value, dest holds the address */ 
    printf("The size of destination is %lu\n",sizeof(dest)); 

    strcpy(dest,buffer); 
    strcpy(dest+buflen,mystring);/* copy the second string to dest after buffer is copied */ 
    printf("The final string is %s\n",dest); /*To print a string use %s, %p is to print pointer*/ 
    return 0; 
}