[英]Dynamic Memory Allocation - When and Why
I am a novice in C and trying to understand basic concepts in C, Like when and Why I have to allocate Memory for a string pointer. 我是C的新手,试图理解C的基本概念,例如何时和为什么我必须为字符串指针分配内存。 here I have a sample program. 在这里,我有一个示例程序。 I have commented in appropriate locations. 我在适当的位置发表了评论。 Please help me understand. 请帮助我理解。
/ Please help me understand why do I have allocate Memory in Case 2 while I don't have to in Case 1.
#include<stdio.h>
void xcopy(char *t,const char *s);
int main(int argc, char const *argv[])
{
char name1[]="Asfakul";
char *name;
char *target;
name=name1; // Here I dont have to allocate Memory (Case 1)
puts(name);
target=(char*)calloc(10,sizeof(char)); // Here I have to allocate Memory (Case 2)
xcopy(target,name);
return 0;
}
void xcopy(char *t,const char *s)
{
while( *s !='\0')
{
*t=*s;
t++;
s++;
}
puts(t);
}
name=name1; // Here I dont have to allocate Memory (Case 1)
In this case , you don't allocate memory to name
, you just make it point to array name1
. 在这种情况下,您无需为 name
分配内存 , 只需使其指向数组 name1
。 In short , name
now has address of first element of array name1
. 简而言之, name
现在具有数组name1
的第一个元素的地址。
target=(char*)calloc(10,sizeof(char)); // Here I have to allocate Memory (Case 2)
xcopy(target,name);
And in case 2
you need to allocate memory as you copy the contents of name1
at the memory block to which target
points to . 在第2
情况下,您需要在target
指向的存储块中复制name1
的内容时分配内存。
Here , it is needed as if you don't allocate memory then target
point to anything ( maybe garbage ) and writing to that location will cause undefined behaviour . 在这里,需要的是好像您没有分配内存,然后将target
指向任何内容( 可能是垃圾 ),并且写入该位置将导致未定义的行为 。
Note - You don't need to free
any memory in case 1
as pointer points to a array on stack . 注意 –在情况1
由于指针指向堆栈中的数组,因此您不需要free
任何内存。 But you need to do free(target);
但是你需要做free(target);
in case 2
as you allocate memory on heap. 在情况2
当您在堆上分配内存时。
In the first case, you start with name1
, which is an array of char
. 在第一种情况下,您从name1
开始,它是char
的数组。 Then you take name
, which is a char *
, and assign name1
to it. 然后,您获取name
,它是一个char *
,并为其分配name1
。 Since name1
is being evaluated in pointer context, it refers to a pointer to the first element of the array. 由于name1
是在指针上下文中求值的,因此它是指向数组第一个元素的指针。 So now name
points to the first element of name1
. 因此,现在name
指向name1
的第一个元素。
In the second case, target
is assigned a memory location returned by a call to calloc
, which in this case is a block of 10 bytes. 在第二种情况下,为target
分配了由对calloc
的调用返回的内存位置,在这种情况下,该内存位置是一个10字节的块。 The bytes now pointed to by target
can now be used. 现在可以使用target
指向的字节。
As with any pointer, you need to assign it a value before you can dereference it. 与任何指针一样,您需要先给它分配一个值,然后才能取消引用它。 That value can be either the address of some other variable, or a block of memory returned by the malloc
family of functions. 该值可以是某些其他变量的地址,也可以是malloc
系列函数返回的内存块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.