0

有人可以告诉我如何纠正这个警告/错误。我试图只获取字符串的第一个字符来判断它是否为“-”。

错误:

grep-lite.c:15:13: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   if(strcmp((char *) pattern[0],"-") == 0)
             ^
grep-lite.c:29:16: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   while(strcmp((char *) argv[index][0],"-"))
                ^

带有警告/错误的来源:

第 15 行:

if (strcmp((char *) pattern[0],"-") == 0)

第 29 行:

while (strcmp((char *) argv[index][0],"-"))

完整来源:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "grep-lite.h"

int main(int argc, char * * argv)
{
  //initailize variables
  int index = 1, lineNumber = 1;
  int oneMatchingLine = FALSE;
  int invertOpt = FALSE, lineNumOpt = FALSE, quietOpt = FALSE;
  char * pattern = argv[argc];

  //check if last arguement is invalid by starting with a '-'
  if(strcmp((char *) pattern[0],"-") == 0)
    {
      error(INVALID_PATTERN);
      return EXIT_ERROR;
    }

  //check if they asked for help
  if(strcmp(argv[index],"--help") == 0)
    {
      printHelpStatement();
      return EXIT_SUCCESS;
    }

    //walk through all options
  while(strcmp((char *) argv[index][0],"-"))
    {
      //find and set option
      if(processOptions(argv[index], &invertOpt, &lineNumOpt, &quietOpt))
    index++;
      //if invalid option fai
      else
    {
      error(INVALID_OPTION);
      return EXIT_ERROR;
    }
    }

  //walk through stdinput searching for pattern relationship
  while(feof(stdin) == 0)
    {
      //initialize
      char * thisLine = NULL;

      // get read line with fgets
      thisLine = fgets(thisLine, MAX_CHARACTERS, stdin);

      //find pattern location in thisLine
      char * patternLoc = strstr(thisLine, pattern);

      //check if we should print this line based of patternLoc and invertOpt
      if((!patternLoc != NULL && !invertOpt) || (pattenLoc == NULL && invertOpt))
    {
      //see if we should print this line
      if(!quietOpt)
        printLine(thisLine, lineNumOpt, lineNumber);
    }
      lineNumber++;
    }
4

1 回答 1

1

我将列举我在您的代码中发现的问题

  1. 正确用法strcmp()存在于您的代码中,在这一行

    if (strcmp(argv[index],"--help") == 0)
    

    strcmp()用于字符串比较,而不是字符比较,这

    if(strcmp((char *) pattern[0],"-") == 0)
    

    应该

    if (pattern[0] == '-')
    

    不要强制编译变量,而是找到编译器错误/警告的实际原因。

  2. 你有一个严重的错误,你没有为thisLine char指针分配空间,你必须通过分配内存malloc()或者只是将它声明为一个char数组

    char thisLine[SOME_CONSTANT_NUMBER];
    

    还有,这

    while(feof(stdin) == 0)
    

    从来都不是一个好主意,而是这样做

    char thisLine[100];
    while (fgets(thisLine, sizeof(thisLine), stdin) != NULL)
    
  3. 您犯了另一个非常常见的错误,c 中的数组是从0to索引的N - 1,所以

    char *pattern = argv[argc]
    

    是错误的,因为您在最后一个元素之后读取一个元素,正确的代码是

    char *pattern = argv[argc - 1]
    

    这将为您提供最后一个元素。

于 2015-02-27T00:10:57.437 回答