簡體   English   中英

從 'char' 到 'char' 的無效轉換 [-fpermissive] 16 | A[++top] = x; | ^ | | | 字符*

[英]Invalid conversion from 'char' to 'char' [-fpermissive] 16 | A[++top] = x; | ^ | | | char*

我正在嘗試將字符串添加到堆棧中。 請告訴我程序中有什么問題。 在這個程序中,我試圖將堆棧實現為數據結構。 我知道如何將數字添加到堆棧和/或刪除它們,但我不知道如何添加字符輸入。 現在我想做一些類似項目列表的事情,然后打印整個列表。

//Array implementation of the stack
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 11

char A[MAX_SIZE];
int top = -1;


void Push(char x[])
{
  if (top == MAX_SIZE - 1) {
    printf("Error! Array size: %d exceeded\n", MAX_SIZE);
    return;
  }
  A[++top] = x;
}

void Pop() {
  if (top == -1) {
    printf("Error! No element to pop\n");
    return;
  }
  top--;
}

char Top()
{
  return A[top];
}

void Print()
{
  int i;
  printf("Stack: ");
  for (i = 0; i <= top; i++)
    printf("%s ", A[i]);
  printf("\n");
}
int main()
{
  char name1[10] = "Pablo";
  Push(name1);
  char name2[10] = "Robert";
  Push(name2);
  Print();
}

從 'char' 到 'char' 的無效轉換 [-fpermissive] 16 | A[++top] = x; | ^ | | | 字符*

您的堆棧A被聲明為一個char數組,因此它只能保存一個字符串(或一個字符數組)。 在有問題的行中,您試圖將char *分配給單個char

您應該將A定義為char *數組:

char *A[MAX_SIZE];

數組的元素

char A[MAX_SIZE];

char ,它只能存儲一個字符。

另一方面,參數xchar*char x[]與函數參數中的char* x具有相同的含義)。 因此發生類型不匹配。

將數組更改為

char* A[MAX_SIZE];

和函數Top to

char* Top()

將使您的程序工作。

請注意,指針將被直接存儲而不是復制字符串,因此請注意不要取消引用指向消失對象的指針。 (這在這段代碼中不會有問題)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM