赋值从没有强制转换的指针生成整数

时间:2014-10-31 07:14:51

标签: c

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。我知道我正在使用指针的值并将其置于整数中,但我该如何解决此错误呢?

4 个答案:

答案 0 :(得分:1)

即使将*dest更改为dest,您的函数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 :(得分: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()声明中的访问说明符。

答案 2 :(得分:0)

更改

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

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

编辑:正如@POW所说,你不需要转换malloc的结果

答案 3 :(得分: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;
}