出版于

Giant Machines

Be Grateful for JavaScript Arrays: A Comparison with C

Demonstration in the USS Midway of how much memory has changed over the years.

Background

  • JavaScript is considered a high-level language, meaning there are a lot of abstractions between you (the developer) and the machine. Which is a fancy way of saying that high-level languages do a lot of work for us. Here’s a greatarticlethat highlights these differences.
  • C需要手动内存管理,而JavaScript提供自动内存管理。稍后再详细介绍。
  • C must be compiled in advance, whereas JavaScript is compiled right before being executed, often referred to as恰到好处compilation.
  • C中的数组可以容纳单个数据类型(char,int,float等),而在JavaScript中,数组可以将混合的数据类型放在框外,例如字符串,数字和布尔值。(但是,C中的数组也可以使用一些工作

推它!

const myArr = [1,2,3,4,5];
myarr.push(6);
console.log(myarr);
// [1,2,3,4,5,6]
#include 
#include

int main(void){

char sizeofintegerpointer = sizeof(int);
int * myarr = malloc(sizeofintegerpointer * 5);

if (myArr == NULL) {
printf(“为数组分配内存有错误”);
退出(exit_failure);
}

for(int i = 0; i <5; i ++){
myarr [i] = i + 1;
}

在t *myArrExpanded = realloc(myArr, sizeOfIntegerPointer * 6);

if(myarrexpanded == null){
printf("There was an error reallocating memory for the array");
退出(exit_failure);
}

myarrexpanded [5] = 6;

for(int i = 0; i <6; i ++){
printf(“%d”,myarrexpanded [i]);
}

免费(myarrexpanded);

return 0;
}

Memory Layout

Stack

将煎饼从堆栈中取出以进入第一个。

Heap

Arrays

C中的固定长度阵列

Variable-Length Arrays in C

在t array_len;printf(“输入所需的数组长度:”);
// C中的“&”操作员是指“地址”。我们将在下面介绍更多
scanf(“%d”,&array_len);
int arr [array_len];

C中的动态阵列

#include 
#include

int main(void){
// Request memory from the OS
// Hello OS! I'm requesting memory for 5 times the size of an integer
char sizeofintegerpointer = sizeof(int);
int * myarr = malloc(sizeofintegerpointer * 5);


//验证分配成功
if (myArr == NULL) {
printf(“为数组分配内存有错误”);
退出(exit_failure);
}

//初始化数组值
for(int i = 0; i <5; i ++){
myarr [i] = i + 1;
}

//将数组值移至新的,扩展的内存位置通过Realloc
在t *myArrExpanded = realloc(myArr, sizeOfIntegerPointer * 6);

if(myarrexpanded == null){
printf("There was an error reallocating memory for the array");
退出(exit_failure);
}

myarrexpanded [5] = 6;

//打印值
for(int i = 0; i <6; i ++){
printf(“%d”,myarrexpanded [i]);
}

//释放内存
免费(myarrexpanded);

return 0;
}

从操作系统请求内存

Check That Allocation Worked

Move Array Values to a Larger Memory Location

Assign and Free Up Memory

与JavaScript进行比较

const myArr = [1,2,3,4,5];
myarr.push(6);
console.log(myarr);
// [1,2,3,4,5,6]

结论

- -

- -

获取中型应用betway娱乐官网

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
一个说“获取它,Google Play”的按钮,如果单击它,它将带您到Google Play商店
Baidu