c-如何增加索引并用指针打印正确的字符串



当c->x将该值增加1,但与c->x,ptr1指针";忘记";其地址。

如何创建一个指向字符串数组的指针而不使用";遗忘;它的地址?

#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("%s n", *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;
//c->x = 1 , prints first message
cursor(&cursxy,ptrMsg);   //ptrMsg point to first message
//c->x = 2 , prints again the first message
cursor(&cursxy,ptrMsg);  //ptrMsg Didn't point to second message  <------------
// and so on
}

表达式之间的差异

c->x++

*ptr1++

后者修改函数参数,而前者不修改。

在C中,函数有自己的用于调用函数的函数参数值的副本。因此,在函数内部修改这些参数不会修改原始变量。

因此,在函数cursor中,对函数自变量ptr1的任何改变都不会改变函数main中的变量ptrMsg

问题的最简单解决方案是在函数main中增加ptrMsg,而不是在cursor中增加。

但是,如果您坚持从cursor内部更改ptrMsg,则必须通过引用而不是通过值传递变量ptrMsg。这意味着您必须将ptrMsg的地址传递给函数cursor,如下所示:

cursor(&cursxy,&ptrMsg);

您还必须更改函数cursor的原型,以便第二个参数具有额外的间接层。此外,您还必须添加一个*解引用运算符,以便通过指针访问原始变量。之后,您的功能将如下所示:

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

这就是您想要的。与cursxy相同,使用双指针。

#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("%s n", *ptr1);
*ptr1 = ++*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;
char (**ptr)[msgLEN] = &ptrMsg;

//c->x = 1 , prints first message
cursor(&cursxy, ptr);   //ptrMsg point to first message
//c->x = 2 , prints second message
cursor(&cursxy, ptr);  //ptrMsg Didn't point to second message  <------------

cursor(&cursxy, ptr);  //ptrMsg Didn't point to second message  <------------
// and so on
}

最新更新