案例1:我写的时候
char*str={"what","is","this"};
Run Code Online (Sandbox Code Playgroud)
然后str[i]="newstring";是有效的,而str[i][j]='j';无效.
案例2:我写的时候
char str[][5]={"what","is","this"};
Run Code Online (Sandbox Code Playgroud)
然后str[i]="newstring";无效,而str[i][j]='J';有效.
为什么会这样?我是一个初学者,在阅读其他答案后已经非常困惑.
我研究了很多静态和动态内存分配,但仍有一个混乱:
int n, i, j;
printf("Please enter the number of elements you want to enter:\t");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
{
printf("a[%d] : ", i + 1);
scanf("%d", &a[i]);
}
Run Code Online (Sandbox Code Playgroud)
是否int a[n]都在静态或动态内存分配?
c memory-management dynamic-memory-allocation static-memory-allocation
我已经研究了所有可能的方法,但是我很难消化malloc ie malloc(sizeof(10))
和calloc都calloc(2,sizeof(5))分配相同的连续内存这一事实,忽略了calloc初始化为零并且比malloc工作相对慢的其他事实.所以这就是我的想法.
我认为在32位系统上,如果我们调用malloc并说malloc(sizeof(10))当时malloc将进入堆并分配12个字节的内存,因为对于32位系统,内存包以4个字节为一组排列,以便分配10个在最后一个块中填充2个字节需要3个字节.
类似地,如果我们调用calloc并说calloc(2,sizeof(5))它将分配2个块,每个块大小为8个字节,总共16个字节,因为由于相同的原因,内存在4个字节的包中,并且分配5个字节,两个4个字节的块是在一个块中使用,将提供3个字节的填充.
所以这就是我对malloc和calloc的看法.我可能是对或错但请告诉我.
c memory pointers memory-management dynamic-memory-allocation
情况1:char s[][6]={"Hello","world"};
在这种情况下,静态数组被分配在只读存储器中,并从那里将元素复制到数组中.在案例2中.
情况2:char* s= "hello world";将它放在只读存储器中.
所以我的问题是为什么
char s[][6]={"Hello","world"};
s[1]="lucky"; //is illegal
Run Code Online (Sandbox Code Playgroud)
因为如果从只读内存复制元素,那么为什么s[1]="lucky";不能将此语句从只读内存复制到数组,因为还为此字符串文字分配了一个数组,并从那里将元素复制到s [1].我已经阅读了很多答案,所有人都在说明有什么区别,但没有人说出原因?请解释,因为我是初学者.