2016-12-03 60 views
-1

(警告)是的,這是我正在做的任務的一部分,但在這一點上我完全絕望,不,我不是在尋找你們爲我解決它,但任何暗示都將非常感激! /警告)爲什麼strlen在C中導致分段錯誤?

我非常想做一個交互式菜單,用戶是爲了輸入一個表達式(例如「5 3 +」),程序應該檢測到它在後綴表示法中,不幸的是我已經得到分段錯誤錯誤,我懷疑它們與使用函數的功能有關。

編輯:我能夠使它發揮作用,首先char expression[25] = {NULL};
成爲char expression[25] = {'\0'};

並調用determine_notation功能,當我刪除該數組中的[25]我路過像這樣: determine_notation(expression, expr_length);

另外input[length]第I部分改爲input[length-2],因爲像之前的評論中提到的input[length] == '\0'input[length--] == '\n'

總之感謝所有的幫助!

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

int determine_notation(char input[25], int length); 

int main(void) 
{ 
    char expression[25] = {NULL}; // Initializing character array to NULL 
    int notation; 
    int expr_length; 

    printf("Please enter your expression to detect and convert it's notation: "); 
    fgets(expression, 25, stdin); 

    expr_length = strlen(expression[25]); // Determining size of array input until the NULL terminator 
    notation = determine_notation(expression[25], expr_length); 
    printf("%d\n", notation); 
} 

int determine_notation(char input[25], int length) // Determines notation 
{ 

    if(isdigit(input[0]) == 0) 
    { 
     printf("This is a prefix expression\n"); 
     return 0; 
    } 
    else if(isdigit(input[length]) == 0) 
    { 
     printf("This is a postfix expression\n"); 
     return 1; 
    } 
    else 
    { 
     printf("This is an infix expression\n"); 
     return 2; 
    } 
} 
+2

'輸入[長度]''是'\ 0''(和:''輸入[長度-1 ]'是''\ n''並且:'expression [25];索引超出對象的大小) – wildplasser

+1

strlen獲取一個字符串(指向第一個字符),而不是一個字符。 –

+1

'char expression [25] = {NULL};'沒有感覺。用'{'\ 0'}'或''''替換爲' – Stargateur

回答

4

你可能得到一個警告,說明您在此調用轉換char的指針:

expr_length = strlen(expression[25]); 
//        ^^^^ 

這就是問題 - 你的代碼是引用一個不存在的元素過去數組的末尾(一個未定義的行爲)並嘗試將它傳遞給strlen

由於strlen需要一個指針到字符串的開頭,該呼叫需要是

expr_length = strlen(expression); // Determining size of array input until the NULL terminator 
+0

我明白了,這已經解決了我的問題的一部分。至少現在它實際上是輸入功能。萬分感謝! – Stoon

相關問題