2017-01-23 86 views
-3

以下代碼正在生成指針警告,我不知道如何解決它?指向堆棧的C指針導致警告

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: %d\n",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; 
} 
+0

你有你的間接性,'*',完全錯誤。閱讀應該如何訪問指針,然後重試。如果您對主題感到困惑,請隨時提問。 一個初學者,你的棧的內存在聲明中不應該有'*',除非你的目標是在你的24元素數組中存儲「指向整數的指針」。 – TezlaCoil

+0

對不起,但沒有任何意義。您不需要在此代碼中修復指針警告。這從一開始到最後都是錯誤的。您需要將其全部廢棄並重新開始。 –

+0

編寫'* ++ s-> point = s-> top;'需要一定量的虛張聲勢(並且確信自己在做什麼)。我很少嘗試在單一操作中做那麼多事情。 –

回答

0

也許你想這一點;

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; 
}; 
1

寫在警告,t->top是一個整數,但*++s->point是一個指針,所以你不能整數轉換爲指針。

0

我張貼一個解決我的問題: 問題是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: %d\n",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; 
}