Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C 访问内存


访问动态内存

动态内存的行为类似于数组,其数据类型由指针的类型指定。

与数组一样,要访问动态内存中的元素,请参考其**索引号**

ptr[0] = 12;

您还可以取消引用指针以访问第一个元素

*ptr = 12;

示例

读取和写入动态内存

// 分配内存
int *ptr;
ptr = calloc(4, sizeof(*ptr));

// 写入内存
*ptr = 2;
ptr[1] = 4;
ptr[2] = 6;

// 从内存读取
printf("%d\n", *ptr);
printf("%d %d %d", ptr[1], ptr[2], ptr[3]);
自己试试 »

关于数据类型的说明

动态内存没有自己的数据类型,它只是一系列字节。内存中的数据可以根据指针的数据类型解释为一种类型。

在此示例中,指向四个字节的指针可以解释为一个int值(4 个字节)或一个包含 4 个char值(每个 1 个字节)的数组。

示例

int *ptr1 = malloc(4);
char *ptr2 = (char*) ptr1;
ptr1[0] = 1684234849;
printf("%d is %c %c %c %c", *ptr1, ptr2[0], ptr2[1], ptr2[2], ptr2[3]);
自己试试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.