小编VMi*_*VMi的帖子

为什么char指针保存的数据比C中分配的内存多?

在C语言中进行动态内存分配时,将内存大小分配给char指针时,我感到困惑。虽然我只给出1个字节作为限制,鉴于每个字母对应于1个字节,char指针成功地尽可能长地获取了输入

我也试图找到输入前后的指针大小。有人可以帮我了解这里发生了什么吗?输出使我感到困惑。

看下面的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int limit;

    printf("Please enter the limit of your string - ");
    gets(&limit);

    char *text = (char*) malloc(limit*4);

    printf("\n\nThe size of text before input is %d bytes",sizeof(text));

    printf("\n\nPlease input your string - ");
    scanf("%[^\n]s",text);

    printf("\n\nYour string is %s",text);

    printf("\n\nThe size of char pointer text after input is %d bytes",sizeof(text));

    printf("\n\nThe size of text value after input is %d bytes",sizeof(*text));

    printf("\n\nThe size of ++text value after input is …
Run Code Online (Sandbox Code Playgroud)

c malloc pointers char

0
推荐指数
1
解决办法
67
查看次数

标签 统计

c ×1

char ×1

malloc ×1

pointers ×1