C语言中的指针

本文总结C语言课程学习中用到的指针概念及操作。

动态分配内存

malloc

  • 功能描述

    分配所要求的内存空间,并返回指向该空间的指针

  • 函数原型

    1
    2
    #include <stdlib.h>
    void *malloc(size_t size)
  • 参数

    • size指的是内存空间的字节大小
  • 返回值

    • 分配成功,返回指向该空间的指针
    • 分配失败,返回NULL
  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #include <stdio.h>
    #include <stdlib.h>

    int main () {
    char *str;

    /* Initial memory allocation */
    str = (char *) malloc(15);
    strcpy(str, "tutorialspoint");
    printf("String = %s, Address = %u\n", str, str);

    /* Reallocating memory */
    str = (char *) realloc(str, 25);
    strcat(str, ".com");
    printf("String = %s, Address = %u\n", str, str);

    free(str);

    return(0);
    }

bool

C语言中没有bool值,不可以使用true / false

unsigned

不要在它减到0时继续往下减,否则会变成无穷大

结构体

结构体中不能包含函数,不推荐在定义结构体后直接声明变量。

结构体作为数据类型,需要在前面加上struct,比如

1
struct Time devide(struct Time t1, struct Time t2){}

循环

不允许在for内定义变量

指针与引用

C语言中没有引用

报错汇总

是否忘记了向源中添加“#include “stdafx.h“”

对于每一个出错的.cpp文件,右键——》属性——》C/C++——》预编译头,选择不使用预编译头即可。

This is a summary

Any content (support inline tags too).