【问题标题】:How to get length of contiguous memory pointed at by char* after initializing it with malloc? [duplicate]使用malloc初始化char *后如何获取char *指向的连续内存的长度? [复制]
【发布时间】:2020-09-27 09:34:47
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* buffer = malloc(1000*sizeof(char));
    memset(buffer,'\0',1000);

    printf("%ld\n",sizeof buffer);    // Size of Pointer
    printf("%ld\n",sizeof *buffer);   // Size of Memory Block pointed at by buffer
    printf("%ld\n",strlen(buffer));   // Length of String
    return 0;
}


//  Output:-
//  8
//  1
//  0

代码运行良好。

输出符合预期,但是如果我不知道长度,如何找到我用 malloc 初始化的连续内存的长度?

【问题讨论】:

  • 你必须把内存大小给malloc,你怎么会在不知道大小的情况下呢?
  • 我将指针传递给另一个函数@Ôrel。
  • 是的,答案是 @kaylum。
  • 我想这是我的错误编码,我应该在我使用它的函数中分配内存并将其传递给修改。

标签: c string memory char malloc


【解决方案1】:

没有标准的方法可以确定一块 malloc 的内存有多大。

由您自己跟踪大小。

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多