簡體   English   中英

將char存儲在整數數組中

[英]storing char in an array of integers

我對此程序有疑問,在這里我們要創建整數數組並在其中存儲char

考慮一下,當我們將后綴寫入后綴程序時,將使用相同的堆棧操作功能

然后將括號和操作數存儲在堆棧中,我想問一下是否將ASCII值存儲在stack->array ,為什么不需要類型轉換,並且由於整數需要4個字節的內存,那么如何將1個字節的char存儲在其中該數組不僅存儲,而且我們如何使用該整數數組訪問所有char變量,因為如果數組是整數指針,根據指針算術*(array+i)將提前4個字節

#include <stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>

// Stack type
struct Stack
{
    int top;
    unsigned capacity;
    int* array;
};

// Stack Operations
struct Stack* createStack( unsigned capacity )
{
    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));

    if (!stack) return NULL;

    stack->top = -1;
    stack->capacity = capacity;
    stack->array = (int*) malloc(stack->capacity * sizeof(int));

    if (!stack->array) return NULL;

    return stack;
}

int isEmpty(struct Stack* stack)
{
     return stack->top == -1 ;
}

char peek(struct Stack* stack)
{
    return stack->array[stack->top];
}

char pop(struct Stack* stack)
{
    if (!isEmpty(stack))
        return stack->array[stack->top--] ;
    return '$';
}

void push(struct Stack* stack, char op)
{
    stack->array[++stack->top] = op;
}


// The main function that returns value of a given postfix expression
int evaluatePostfix(char* exp)
{
    // Create a stack of capacity equal to expression size
    struct Stack* stack = createStack(strlen(exp));
    int i;

    // See if stack was created successfully
    if (!stack) return -1;

    // Scan all characters one by one
    for (i = 0; exp[i]; ++i)
    {
        // If the scanned character is an operand (number here),
        // push it to the stack.
        if (isdigit(exp[i]))
            push(stack, exp[i] - '0');

        // If the scanned character is an operator, pop two
        // elements from stack apply the operator
        else
        {
            int val1 = pop(stack);
            int val2 = pop(stack);
            switch (exp[i])
            {
                case '+': push(stack, val2 + val1); break;
                case '-': push(stack, val2 - val1); break;
                case '*': push(stack, val2 * val1); break;
                case '/': push(stack, val2/val1); break;
            }
        }
    }
    return pop(stack);
}

// Driver program to test above functions
int main()
{
    char exp[] = "231*+9-";
    printf ("Value of %s is %d", exp, evaluatePostfix(exp));
    return 0;
}

char是機器中可包含基本字符集的最小可尋址單元。 它是一個整數類型 實際類型可以是帶符號的也可以是無符號的。 它包含CHAR_BIT位。

它的大小幾乎總是小於int的大小。 因此,可以將char輕松存儲在int

我們如何使用該整數數組訪問所有char變量,因為如果數組是指向整數的指針,則根據指針算術*(array + i)將提前4個字節

這是可能的,因為在將char存儲到int ,將以int大小的間隔存儲它們。 由於top是一個int ,因此其上的指針算法(++)將其地址值增加一個int的大小。

stack->array[++stack->top] = op;

這就是在您同時檢索char時發生的情況。 top的指針運算top (-)將其地址值減小一個int的大小。

return stack->array[stack->top--] ;

因此它可以正常工作。

暫無
暫無

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

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