[英]Segmentation fault error with pointer array in C
我正在嘗試從find_char函數“ C上的指針”測試一些代碼,該函數搜索指定的字符。 我添加了自己的東西,即main()函數,該函數調用find_char並包括要搜索的初始化數據(指向char的指針數組)。 我設法在編譯時修復了所有錯誤和警告,但是在嘗試運行a.out文件時,出現了段錯誤錯誤。
我知道分段錯誤主要與數組和指針有關,當類型轉換不正確時,這種錯誤經常發生。 但是我真的找不到我的代碼有什么問題。
非常感謝。
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int find_char( char **strings, char value);
int main(void)
{
int i;
char c = 'z';
char *pps[] = {
"hello there",
"good morning",
"how are you"
};
i = find_char(pps, c);
printf("%d\n", i);
return 0;
}
int find_char (char **strings, char value)
{
char *string;
while (( string = *strings++) != NULL)
{
while (*string != '\0')
{
if( *string++ == value )
return TRUE;
}
}
return FALSE;
}
好吧,您的問題來自外部的while循環。 它遍歷數組中的字符串,直到找到NULL
字符串為止。 但是,您並沒有使用這樣的字符串終止數組,因此循環將在第三個字符串之后繼續進行,並最終嘗試訪問原本不應該的內存。
解決問題的方法:您可以通過給函數提供size
參數來修改函數的簽名,以使其變為
int find_char(const **char strs, int size, char ch);
然后,您需要在循環過程中包括此大小值,以找到停止條件。
char *s = NULL;
int i = 0;
while (i++ < size && (s = *strs++)) {
// ...
}
這里要記住的一點是,在C編程中,需要仔細地使用內存和數組。 在處理數組時,通常希望將數組的大小作為參數傳遞給每個處理函數。
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.