1

【C】一些特性

 2 years ago
source link: https://www.guofei.site/2021/12/18/c_more.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【C】一些特性

2021年12月18日    Author:Guofei

文章归类: 语言    文章编号: 12001


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2021/12/18/c_more.html

Edit

关于变量类型

for (int i = 0; i < 10; i++) {
    static int a = 10;
    a++;
    printf("%d\n", a);
}
// >11, 12, 13, 14, 15, 16, 17, 18, 19, 20,

for (int i = 0; i < 10; i++) {
    int a = 10;
    a++;
    printf("%d\n", a);
}
// >11, 11, 11, 11, 11, 11, 11, 11, 11, 11,

这是因为, static 只会初始化1次,无论它在哪

关于指针

二级指针避免内存泄露

错误的代码

void tst(char *i) {
    i = malloc(100); // 这个 i 运行完毕后被清空了
}

int main() {
    char *p = NULL;
    tst(p);
    strcpy(p, "hello"); // 这个 p 仍然为0
    free(p); // 释放不是 malloc 分配的内存
    return 0;
}

正确的代码:用二级指针

void tst(char **i) {
    *i = malloc(100);
}

int main() {
    char *p = NULL;
    tst(&p);
    strcpy(p, "hello");
    free(p);
    return 0;
}

您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK