You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何让字符串数组指针自增后保留地址 正确打印对应字符串

问题解决方案

根因分析

C语言参数默认采用值传递规则,你传入cursor函数的ptrMsg是外层指针的临时副本,函数内对ptr1的自增仅作用于副本,不会修改外层main函数中ptrMsg的实际指向,因此每次调用都会重复打印第一个字符串。

解决方法

提供两种可选实现:

方案1:传入二级指针直接修改外层原指针

修改函数参数为指向数组指针的二级指针,操作时直接解引用修改外层原指针的值:
修改后的函数定义:

void cursor(struct cursxy *c, char (**ptr1)[msgLEN])
{
    c->x++;
    // 先解引用拿到外层原指针,打印后自增原指针
    printf("%s \n", *(*ptr1)++);
}

调用时传入外层指针的地址:

cursor(&cursxy, &ptrMsg);

方案2:通过返回值传递更新后的指针

修改函数返回值为数组指针类型,将自增后的指针返回给外层接收:
修改后的函数定义:

// 返回值为指向长度msgLEN的char数组的指针
char (*cursor(struct cursxy *c, char (*ptr1)[msgLEN]))[msgLEN]
{
    c->x++;
    printf("%s \n", *ptr1++);
    return ptr1;
}

调用时用外层指针接收返回值:

ptrMsg = cursor(&cursxy, ptrMsg);

完整运行示例(方案1)

#include <stdio.h>
#define msgROW 5
#define msgLEN 16

struct cursxy{
   unsigned int x;
   unsigned int y;
};

void cursor(struct cursxy *c,char (**ptr1)[msgLEN])
{
   c->x++;
   printf("x=%d, %s \n", c->x, *(*ptr1)++);
}

int main()
{
   struct cursxy cursxy = {0,0};       

   char messages[msgROW][msgLEN] =
    { 
        "Set Duty Cycle", 
        "Set Frequency",  
        "Set Hours",        
        "Set Minutes",     
        "Set Current"     
    };  

    char (*ptrMsg)[msgLEN] = messages;

    cursor(&cursxy, &ptrMsg);
    cursor(&cursxy, &ptrMsg);
    cursor(&cursxy, &ptrMsg);
    cursor(&cursxy, &ptrMsg);
    cursor(&cursxy, &ptrMsg);

    return 0;
}

运行后将依次打印5条配置项字符串,c->x的值同步从1递增到5。

内容的提问来源于stack exchange,提问作者Luigi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:24:06