基本 C 从 int 转换警告指针

Basic C cast warning pointer from int

谁能告诉我如何更正这个 warning/error。我试图只获取字符串的第一个字符来判断它是否为“-”。

错误:

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],"-"))
                ^

来源 warnings/errors:

第 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++;
    }

我会列举我在你的代码中发现的问题

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

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

    strcmp()是为了字符串比较,不是字符比较,这个

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

    应该是

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

    不要转换变量来强制编译,而是寻找编译器的实际原因 error/warning。

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

    char thisLine[SOME_CONSTANT_NUMBER];
    

    还有这个

    while(feof(stdin) == 0)
    

    从来都不是好事idea而是这样做

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

    char *pattern = argv[argc]
    

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

    char *pattern = argv[argc - 1]
    

    这会给你最后一个元素。