English 中文(简体)
C中小型(小型)的有用例子是什么?
原标题:What are some useful examples of malloc() in C?
  • 时间:2010-11-03 07:28:04
  •  标签:
  • c
  • malloc
最佳回答

Dynamic data structures (lists, trees, etc.) use malloc to allocate their nodes on the heap. For example:

/* A singly-linked list node, holding data and pointer to next node */
struct slnode_t
{
    struct slnode_t* next;
    int data;
};

typedef struct slnode_t slnode;

/* Allocate a new node with the given data and next pointer */
slnode* sl_new_node(int data, slnode* next)
{
    slnode* node = malloc(sizeof *node);
    node->data = data;
    node->next = next;
    return node;
}

/* Insert the given data at the front of the list specified by a 
** pointer to the head node
*/
void sl_insert_front(slnode** head, int data)
{
    slnode* node = sl_new_node(data, *head);
    *head = node;
}

考虑在清单中添加以下新数据:sl_insert_front。 你们需要创造一条将数据保存的节点和名单上下一个节点的点子。 你们会在哪里创立?

  • Maybe on the stack! - NO - where will that stack space be allocated? In which function? What happens to it when the function exits?
  • Maybe in static memory! - NO - you ll then have to know in advance how many list nodes you have because static memory is pre-allocated when the program loads.
  • On the heap? YES - because there you have all the required flexibility.

<代码>小型在C中用于分配坡道——可在运行时间动态增长和缩小的记忆空间,其所有权完全由方案管理员控制。 更多例子说明这一点是有用的,但我在这里显示的是代表。 最后,在复杂的C方案中,你发现,大多数方案的数据都是通过点子提供的。 正确方案始终知道哪一个点子“拥有”数据,一旦不再需要,将仔细清理所分配的记忆。

问题回答

What if you don t know the size of the array when you write your program ? As an example, we could imagine you want to load an image. At first you don t know its size, so you will have to read the size from the file, allocate a buffer with this size and then read the file in that buffer. Obviously you could not have use a static size array.

EDIT:

另一点是:当你使用动态分配时,在分配阵列时,记忆分配在阵列上。 当你以嵌入装置进行方案规划时,这一点非常重要,因为 st的大小可能与肥皂相比有限。

我建议,请见https://stackoverflow.com/questions/79923/what-and- where-are-the-stack-and-heap>Stack和Heap

int* heapArray = (int*)malloc(10 * sizeof(int));
int stackArray[10];

两者在获得数据方面非常相似。 这些数据在存放在现场时有很大的不同。 蒸汽管的配电量是按蒸气分配的,只有在申请到期时,或当要求<代码>(免费(免费)(英文)时,才算出。 阵列被分配在 st上,在 st平时被分配。

如你所描述的<代码>int 阵列[10]在你离开时就消失了。 如果你希望所利用的记忆超出当地范围,那么你必须使用小面积;

虽然你能够使用C99的变量长度阵列,但对于更动态的数据结构来说,仍然没有任何适当的替代。 一个典型的例子是相关名单。 为了达到任意规模,你使用<代码>小分配each node,以便你能够插入和删除不作大量记忆复制的编号,就像一个可变的长度阵列那样。

For example, an arbitrarily sized stack using a simple linked list:

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

typedef struct sNode {
    int payLoad;
    struct sNode *next;
} tNode;

void stkPush (tNode **stk, int val) {
    tNode *newNode = malloc (sizeof (tNode));
    if (newNode == NULL) return;
    newNode->payLoad = val;
    newNode->next = *stk;
    *stk = newNode;
}

int stkPop (tNode **stk) {
    tNode *oldNode;
    int val;
    if (*stk == NULL) return 0;
    oldNode = *stk;
    *stk = oldNode->next;
    val = oldNode->payLoad;
    free (oldNode);
    return val;
}

int main (void) {
    tNode *top = NULL;
    stkPush (&top, 42);
    printf ("%d
", stkPop (&top));
    return 0;
}

现在,有可使用<> > /m> ,可使用可变的长度阵列,但如同在COBOL中书写一个运行系统一样,这样做有更好的办法。

无论何时使用小型设备:

  1. You need dynamic memory allocation
    If you need to create array of size n, where n is calculated during your program execution, the only way you can do it is using malloc().

  2. You need to allocate memory in heap
    Variables defined in some functions live only till the end of this function. So, if some "callstack-independent" data is needed, it must be either passed/returned as function parameter (which is not always suitable), or stored in heap. The only way to store data in heap is to use malloc(). There are variable-size arrays, but they are allocated on stack.





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签