以下代码正在生成指针警告,我不确定如何解决?
gcc -std=c11 -pg -g3 -ggdb -W -Wall -lefence -I. -o main.o -c main.c
main.c: In function ‘push_state’:
main.c:15:16: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
*++s->point = s->top;
^
main.c: In function ‘pop_state’:
main.c:19:11: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
s->top=*s->point--;
^
#include <stdio.h>
typedef struct stack{
int **point; // pointer to location in memory
int *memory[24]; // stack memory
int top;
int i;
}Stack;
void push_state(Stack *s){
s->top=s->i++;
*++s->point = s->top;
};
void pop_state(Stack *s){
s->top = *s->point--;
};
void get_top(Stack *s){
printf("Stack top: %dn",s->top);
};
void start(){
Stack s;
s.point=&s.memory[0];
s.i=0;
push_state(&s);
get_top(&s);
pop_state(&s);
get_top(&s);
}
int main( int argc, char *argv[] ) {
start();
return 0;
}
如警告中所述,t->top
是整数,但*++s->point
是指针,因此无法将整数转换为指针。
也许你想要这个;
typedef struct stack{
int **point; // pointer to location in memory
int *memory[24]; // stack memory
int *top;
int i;
}Stack;
void push_state(Stack *s){
s->top=s->memory[s->i++];
*++s->point = s->top;
};
我正在发布我的问题的解决方案:问题在于,s.point=&s.memory[0];
不正确,也应该s.point=s.memory;
**point
不正确,它应该*point
,*memory[24];
应该动态*memory
和声明。感谢乔纳森·莱夫勒(Jonathan Leffler)让我回去重新考虑一下,从**point
中删除多余的*
。
#include <stdio.h>
#include <stdlib.h>
#define push(s) (*++s->point = s->top)
#define pop(s) (*s->point--)
#define look(s) (*s->point)
#define MALLOC(p,s) if(((p) = malloc(s * sizeof(p))) == NULL){ exit(EXIT_FAILURE); }
typedef struct stack{
int *point; // pointer to location in memory
int *memory; // stack memory
int top;
int i;
}Stack;
void push_state(Stack *s){
++(s->top);
push(s);
};
void pop_state(Stack *s){
s->top = pop(s);
};
void look_top(Stack *s){
printf("look %d, Stack top: %dn",look(s), s->top);
};
void start(){
Stack s;
s.top=0;
MALLOC(s.memory,24);
//s.point=&s.memory[0]; <- wrong assignment
s.point=s.memory;
push_state(&s);
push_state(&s);
push_state(&s);
look_top(&s);
pop_state(&s);
look_top(&s);
pop_state(&s);
look_top(&s);
push_state(&s);
look_top(&s);
}
int main( int argc, char *argv[] ) {
start();
return 0;
}