在 C 中比较字符串时崩溃

Crash when comparing strings in C

好的,所以我正在尝试编写一个函数来检查字符串数组中是否存在单词的字母(它对单词中的每个字母都这样做)。修改了一段时间后,我发现它在尝试使用 strcmp() 时崩溃了。我不知道我做错了什么,因为我刚开始学习 C,所以任何帮助将不胜感激。这是函数:

char SingleChar(char *lex, int wordnum,char *word){
int i,j,k;
for(i=0;i<strlen(word);i++){
    for(j=0;j<wordnum;j++){
        for(k=0;k<strlen(lex[j]);k++){
            if(strcmp(word[i],lex[k])){
                return word[i];
            }
        }
    }
}
return 0;   
}

C 中没有真正的字符串类型。 C 中的字符串只是一个字符数组。 字符串数组将是指向内存中字符数组的指针数组。

如果您想检查 "strings" 数组中的字母。 您可能需要一个指针,它遍历数组的每个字母并比较每个字符。

strcmp() 函数将 return 真 (1) 或假 (0),具体取决于字符串是否相等。

所以我认为你想要的是让你的程序将你的单词的字符与字符串数组中的每个其他单词进行比较。

这个程序遍历整个单词然后告诉你这个字母是否存在。 对于您输入的任何单词的每个字母。

--

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

/*
Function to check for a letter of a word 
in an array of strings */

void singleChar(char *word,int arrlength, char *strings[])
{
  int length = 0;
  length = strlen(word); /* Calculates the length of the string */


for(int y = 0; y < arrlength ; y++) /*Increments to the next word in the              array */
{
    for(int i=0; i <= length ; i++) /*increments to the next letter of the     word you want to check */
    {
     for(int x=0; x < strlen(strings[y]) ; x++) /*Increments x based on the     length of the string */
     {
      char *p = strings[y];
      if(word[i] == p[x]) /*Compares the the first letter of both strings */ 
      {
       printf("The letter %c exists.\n", word[i]);
      }
    }
   }
  }
}

int main ( void )
{
 /*Example */

 char *p = "Hello";
 char *a[2];
 a[0]="Hello";
 singleChar(p, 1,a);


}

看不到字符串数组...您的 C 文件应该大致如下所示:

#include <stdio.h>
char SingleChar(char *lex, int wordnum, char *word){"your function in here"};

int main(){
    // Declare your variables here  
    // Call your function here SingleChar(params) 
    return 0; 
}

比较字符:

if(word[i]==lex[k]){ 
   return word[i];
   break; 
}

除此之外,不太确定您要用您的函数做什么。你需要更具体,我没有看到你输入的字符串数组。

你对char *的意思有误解。它是指向字符的指针。在 C 中,字符串只是一个指向字符的指针,由其他字符和空终止符组成。在您的情况下,这意味着 lex 是单个字符串,而不是字符串列表。

char *a = "imastring";表示a是包含字符[i][m][a][s][t][r][i][n][的一段连续内存的地址g][\0]。在 C 中,空终止符用于表示字符串的结尾。

这意味着当您调用 strlen(lex[j]) 时,您只是引用 lex 中的单个字符,然后读取到字符串的末尾,因此您的结果将单调递减。

您可能想要做的是使用双指针。 char ** list 将指向一个地址,该地址指向一个引用连续字符块的地址。

char ** list = (char **)malloc(sizeof(char *) * 5); 会分配给你 5 个连续的内存地址,然后可以指向字符串本身。您可以按如下方式为它们分配值。

list[0] = a

希望对您有所帮助。