来自int的基本C转换警告指针

时间:2015-02-27 00:09:56

标签: c casting comparison compiler-warnings char-pointer

有人可以告诉我如何更正此警告/错误。我试图得到一个字符串的第一个字符来判断它是否是" - "。

错误:

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

1 个答案:

答案 0 :(得分:1)

我将列举我在代码中找到的问题

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

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

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

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

    应该是

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

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

  2. 您遇到严重错误,没有为thisLine char指针分配空间,您必须通过malloc()分配内存,或者只是将其声明为{{} 1}}数组像

    char

    另外,这个

    char thisLine[SOME_CONSTANT_NUMBER];
    

    永远不是一个好idea而是像这样做

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

    N - 1

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

    char *pattern = argv[argc]
    

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