跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压TASTEWINM文件管理开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间投资TASTESTOCK股票自动交易桌面应用开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳TASTEWINM以键盘为主、用两个窗格整理文件的文件管理器

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

投资

TASTESTOCK何时、做什么——按你定下的规则运行的股票自动交易

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策关于我们隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
昨天
累计浏览
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

C 文档
C
Getting StartedSyntax BasicsTypes and DataModules and LibrariesErrors and TestingKey Concepts: Pointers and Memory
讨论

C 指南 · 6/6

Key Concepts: Pointers and Memory

本章目前仅提供英文版。

Pointers and manual memory management define C, and cause most of its bugs. Once pointers click, arrays, strings, and dynamic structures turn out to be one idea.

Addresses and pointers

Every object lives at some address. &x yields the address of x, a pointer stores it, and *p (dereferencing) reads or writes the object it points to.

#include <stdio.h>

void swap(int *a, int *b) {   /* modifies the caller's variables */
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 10, y = 20;
    int *p = &x;          /* p holds the address of x */

    printf("address of x: %p\n", (void *)p);
    *p = 15;              /* x is now 15 */
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);   /* x=20 y=15 */

    return 0;
}

Arguments are still passed by value, but a copied address still reaches the caller's object. Use NULL for pointers with no target and check before dereferencing.

Pointer arithmetic and arrays

Pointer arithmetic counts elements, not bytes: for an int *p, p + 1 is the next int. An array name usually converts to a pointer to its first element, so a[i] is *(a + i).

#include <stdio.h>

int sum(const int *begin, const int *end) {
    int total = 0;
    for (const int *p = begin; p != end; p++) {
        total += *p;
    }
    return total;
}

int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    size_t n = sizeof a / sizeof a[0];

    int *p = a;                         /* same as &a[0] */
    printf("%d %d\n", *(p + 2), a[2]);  /* 3 3 */

    printf("%d\n", sum(a, a + n));      /* a + n: one past the end */
    return 0;
}

A pointer may point into an array or one past its end, but that last position is for comparisons only. Subtracting two pointers gives a ptrdiff_t element count, and only within the same array.

malloc and free

Data sized at run time, or that outlives its function, goes on the heap (<stdlib.h>):

  • malloc(size) allocates size bytes with indeterminate contents.
  • calloc(count, size) allocates and zero-fills.
  • realloc(ptr, size) resizes, possibly moving the block to a new address.
  • free(ptr) releases the block; free(NULL) is a no-op.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t cap = 4, len = 0;
    int *items = malloc(cap * sizeof *items);
    if (items == NULL) return 1;        /* allocation can fail */

    for (int v = 1; v <= 10; v++) {
        if (len == cap) {
            size_t new_cap = cap * 2;
            int *tmp = realloc(items, new_cap * sizeof *tmp);
            if (tmp == NULL) {          /* items is still valid */
                free(items);
                return 1;
            }
            items = tmp;
            cap = new_cap;
        }
        items[len++] = v * v;
    }
    printf("len=%zu cap=%zu last=%d\n", len, cap, items[len - 1]);

    free(items);
    items = NULL;                       /* guard against reuse */
    return 0;
}
对本章有疑问?
上一章Errors and Testing

Assigning realloc straight back to the original pointer leaks the block on failure, hence the temporary. sizeof *items stays right if the element type changes.

Ownership conventions

Nothing frees memory for you, so every allocation needs a clear owner:

  • Pair every xxx_create that allocates with an xxx_destroy.
  • A const T * parameter is borrowed: the function neither frees nor keeps it.
  • Each block has exactly one owner that releases it.
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *name;      /* owned; freed in player_destroy */
    int score;
} Player;

/* Returns a new Player or NULL. Caller releases it with player_destroy. */
Player *player_create(const char *name, int score) {
    Player *p = malloc(sizeof *p);
    if (p == NULL) return NULL;
    p->name = malloc(strlen(name) + 1);
    if (p->name == NULL) {
        free(p);
        return NULL;
    }
    strcpy(p->name, name);       /* safe: buffer sized exactly */
    p->score = score;
    return p;
}

void player_destroy(Player *p) {
    if (p == NULL) return;
    free(p->name);
    free(p);
}

Undefined behavior to avoid

Undefined behavior (UB) means the standard places no requirements on the result: code can work today and break under another compiler or optimization level.

MistakeExamplePrevention
Null dereference*p with p == NULLCheck before dereferencing
Out-of-bounds accessa[n]Pass lengths and check them
Use after freefree(p); p->xSet pointers to NULL after freeing
Double freefree(p); free(p);Give each block one owner
Uninitialized readint x; x + 1Initialize at declaration
Returning a local's addressreturn &local;Allocate or use a caller buffer
Signed overflowINT_MAX + 1Check ranges before the operation
Modifying a string literalchar *s = "hi"; s[0] = 'H';Use char s[] = "hi";

Warnings, sanitizers, and tools like Valgrind catch most of these during development.

Summary

  • Pointers hold addresses: & takes one, * dereferences. Check for NULL first.
  • Pointer arithmetic is valid only within an array or one past its end.
  • Check every malloc, route realloc through a temporary, and free each block exactly once.
  • Make ownership explicit with create/destroy pairs.
  • Find undefined behavior with tools; prevent it with discipline.

Further reading

  • cppreference: C reference, language and library
  • GCC online documentation, compiler options and warnings
  • Clang AddressSanitizer
  • Clang UndefinedBehaviorSanitizer
  • SEI CERT C Coding Standard, rules for secure C
  • ISO/IEC JTC1/SC22/WG14, the C committee and standard drafts

0 条评论

热门评论最新优先

登录 · 登录后即可发表评论。