一些指针函数常见的错误

指针函数的概念

本质是函数,函数返回值是指针。类比着指针数组。指针数组:本质是数组,数组中每个元素是指针。指针数组定义格式:数据类型 *数组名[元素个数];

定义格式

数据类型 *函数名(参数列表)

{

函数体;

return 地址; //当失败时一般返回NULL

}

错误案例

案例1:

#include <stdio.h>

char *fun()
{
    char buf[32] = "hello";

    return buf;
}

int main(int argc, char const *argv[])
{
    char *p = fun();
    printf("%s\n", p);

    return 0;
}

主函数里的*p指向的是空输不错想要的hello的结果

案例2:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void create_space(char *p) //p=NULL
{
    p = (char *)malloc(32); //改变p的指向,让p指向开辟的堆区
    if (NULL == p)
        printf("malloc err");

    strcpy(p, "hello");
}

int main(int argc, char const *argv[])
{
    char *q = NULL;

    create_space(q); //函数调用后,q依然指向NULL
    //因为p和 q是两个空间,改变函数内的p是不影响函数外的q
    printf("%s\n", q);

    return 0;
}

报段错误:因为q指向NULL, 函数内改变形参p的指向不会影响到q,q还是指向NULL。

可以通过二级指针进行改错

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void create_space(char **p)  //p=&q
{
    *p = (char *)malloc(32);   //*p = *&q = q
    if (NULL == *p)
        printf("malloc err");

    strcpy(*p, "hello");
}

int main(int argc, char const *argv[])
{
    char *q = NULL;

    create_space(&q);   
    //调用函数后,q指向函数内开辟的堆区。因为函数内通过传递q的地址找到q, 让q真的指向开辟的堆区了。
    printf("%s\n", q);

    return 0;
}

案例3:

#include <stdio.h>

void fun(int arr[5]) //arr类型是int *
{
    arr[0] = 100;
    printf("%ld\n", sizeof(arr));
}

int main(int argc, char const *argv[])
{
    int a[5] = {1, 2, 3, 4, 5};
    fun(a);
    printf("%d\n", a[0]);

    return 0;
}

传递数组的形式是为了让用户知道要传递的是一个数组,但本质还是传递数组的首地址,也就是传递指针。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值