2014-10-31 116 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; 
}