读取访问冲突字符串指针

时间:2017-11-29 18:55:07

标签: c pointers access access-violation

我试图运行此函数,在字符串中打印char的索引。 当它为字符串的第一个索引运行并打印索引时,在将字符串指针递增1之后(继续从它离开的位置读取字符串)它会抛出我的消息:

"访问冲突读取位置0x00000000066FF2E9。"当它第二次返回while循环时。

我之前做过这类事情并且有效,我缺少什么? 我不认为我用指针超过了字符串的长度所以不应该是我所知道的问题... 非常感谢任何帮助!

void printIndexesOfChar(char* string, char findIndex)
{
char* temp = string;
  while(strlen(temp) > 0)   
  {
      printf("%s \n", temp);                //prints what is left of the string to check
      temp = strchr(temp, findIndex);       //get pointer to the char we are looking for to calculate index

      if (temp != NULL)                     //if strchr didn't return NULL
      {
          printf("the char %c is located at index %d\n\n", findIndex, (temp - string));   //prints index
          temp++;                           //continue the string after the char index we found in the next iteration
      }
      else
      {
          break;                            //exits while if no more chars in the string
      }
  }
}

主要:

#include <stdio.h>
#include <string.h>
#define MAX_CHARS_STR 40
void main()
{
        char str[MAX_CHARS_STR];
        char indexChar;

        printf("\nProgram 3 Selected.\n\nPlease enter a string of characters for the indexes to be shown.\n");
        scanf("%s", str);
        printf("\nType which character index to print:");
        indexChar = getche();
        printf("\n");
        printIndexesOfChar(str, indexChar);
}

0 个答案:

没有答案