[英]Dynamic Memory Allocation - When and Why
我是C的新手,試圖理解C的基本概念,例如何時和為什么我必須為字符串指針分配內存。 在這里,我有一個示例程序。 我在適當的位置發表了評論。 請幫助我理解。
/ 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)
在這種情況下,您無需為 name
分配內存 , 只需使其指向數組 name1
。 簡而言之, name
現在具有數組name1
的第一個元素的地址。
target=(char*)calloc(10,sizeof(char)); // Here I have to allocate Memory (Case 2)
xcopy(target,name);
在第2
情況下,您需要在target
指向的存儲塊中復制name1
的內容時分配內存。
在這里,需要的是好像您沒有分配內存,然后將target
指向任何內容( 可能是垃圾 ),並且寫入該位置將導致未定義的行為 。
注意 –在情況1
由於指針指向堆棧中的數組,因此您不需要free
任何內存。 但是你需要做free(target);
在情況2
當您在堆上分配內存時。
在第一種情況下,您從name1
開始,它是char
的數組。 然后,您獲取name
,它是一個char *
,並為其分配name1
。 由於name1
是在指針上下文中求值的,因此它是指向數組第一個元素的指針。 因此,現在name
指向name1
的第一個元素。
在第二種情況下,為target
分配了由對calloc
的調用返回的內存位置,在這種情況下,該內存位置是一個10字節的塊。 現在可以使用target
指向的字節。
與任何指針一樣,您需要先給它分配一個值,然后才能取消引用它。 該值可以是某些其他變量的地址,也可以是malloc
系列函數返回的內存塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.