c - 这是一个可接受的 malloc 示例吗?

标签 c arrays dynamic

以下代码是否可以接受。也就是说,这是执行 malloc 的正确方法吗?

这是我可以为我的情况工作的最少代码。我认为这是“正确的方法”,但我是 C 的 super 新手,总体上没有太多线索。我阅读了几个相关的 SO 帖子,但似乎没有一个完全符合这种情况。评论?

#include <stdio.h>

// example of calling a function that creates a dynamically sized array and
// returns it to a caller that doesn't know or care about the size of the array

char* return_char_array(){
     // for the sake of the example, we determined the size to be 100
     char *f=malloc(100*sizeof(char));
     // stick something in the first couple of elements for test purposes
     *f=65;
     *(f+1)=66;
     return f;
}

int main(){
    // we want this function to remain ignorant of the size or other workings 
    // of the array, so, no '[]' or 'malloc'
    char *wipc = return_char_array();
    // well i guess it cares a little, because we assume there are at least 2 elements...
    printf("%c,%c\n",*(wipc),*(wipc+1));
    system("PAUSE");
    return 0;
}

最佳答案

Comments?

使用 f[0] 代替 *ff[1] 代替 *(f + 1)wipc 也是如此。不要忘记调用 free

关于c - 这是一个可接受的 malloc 示例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11331064/

相关文章:

c++ - 在mysql服务器源代码中找不到 'ib_lock_t'的定义

c - 对运动 vector 进行分组

c++ - 如何将零大小的数组传递给模板函数

C# - 将 .NET 程序集加载到单独的 AppDomain 中以便卸载它

javascript - 动态内容被抛出表格之外

database - 如何从 vb.net 中的 tablelayoutpanel 中的文本框访问值

c - sizeof(*v) 在 C 中意味着什么?

c - 使用命令行参数声明结构

java - 在java中创建类的实例时遇到问题

C 字母数组排序