关于malloc和sizeof的新手问题 [英] newbie questions about malloc and sizeof

查看:130
本文介绍了关于malloc和sizeof的新手问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能向我解释为什么我的电话与6返回4字节的的sizeof的字符串大小的malloc?事实上,任何整型参数,我给我的malloc得到4.接下来一个sizeof的,我试图复制两个字符串。为什么我被复制字符串(NULL)的输出中?
以下是我的code:

  INT的main()
{
    char *之海峡=字符串;
    字符*副本=的malloc(sizeof的(STR)+ 1);
    的printf(字节分配给拷贝数:%d \\ n,sizeof的(复印件));
    而(* STR!='\\ 0'){
        *副本= *海峡;
        海峡++;
        复制++;
    }
    副本='\\ 0';
    的printf(%S \\ n,复印件);
}


解决方案

的sizeof(STR)返回类型的指针字符的大小* 。你应该做的是的malloc 字符串的大小是自我:

 的char *副本=的malloc(strlen的(STR)+ 1);

此外,这些行:

 而(* STR!='\\ 0'){
        *副本= *海峡;
        海峡++;
        复制++;
}
副本='\\ 0';

可以用C轻易改写这样的:

 而(*副本++ = * STR ++);

Can someone explain to me why my call to malloc with a string size of 6 returns a sizeof of 4 bytes? In fact, any integer argument I give malloc I get a sizeof of 4. Next, I am trying to copy two strings. Why is my ouput of the copied string (NULL)? Following is my code:

int main()
{
    char * str = "string";
    char * copy = malloc(sizeof(str) + 1);
    printf("bytes allocated for copy: %d\n", sizeof(copy));
    while(*str != '\0'){
        *copy = *str;
        str++;
        copy++;
    }
    copy = '\0';
    printf("%s\n", copy);
}

解决方案

sizeof(str) returns the size of a pointer of type char*. What you should do is to malloc the size of the string it self:

char * copy = malloc(strlen(str) + 1);

Also, these lines:

while(*str != '\0'){
        *copy = *str;
        str++;
        copy++;
}
copy = '\0';

Can be rewritten easily in C like this:

while(*copy++ = *str++);

这篇关于关于malloc和sizeof的新手问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆