可以在数组开始之前向后迭代到一个

Ang*_*ber 2 c arrays pointers

例如,我有一个字符串的ptr并将ptr移动到字符串中的最后一个字符并使用*p--向后迭代到字符串的开头,并且我在数组开始之前迭代到位置1这样可以吗?或者我会获得访问冲突?我只是移动指针 - 不访问.它似乎在我的代码中工作,所以想知道它是不是很糟糕的做法?

这是一个带有*next-- = rem +'A'的样本行; 是一个我在质疑如果好吗???

#include <stdio.h>     /* printf */
#include <string.h>    /* strlen, strcpy */
#include <stdlib.h>    /* malloc/free */
#include <math.h>      /* pow */

/* AAAAA (or whatever length) = 0, to ZZZZZ.  base 26 numbering system */
static void getNextString(const char* prev, char* next) {
   int count = 0;
   char tmpch = 0;

   int length = strlen(prev);
   int i = 0;
   while((tmpch = *prev++) != 0) {
      count += (tmpch - 'A') * (int)pow(26.0, length - i - 1);
      ++i;
   }

   /* assume all strings are uppercase eg AAAAA */
   ++count;

   /*if count above ZZZ... then reset to AAA... */
   if( count >= (int)pow(26.0, length))
      count = 0;

   next += (length-1);  /* seek to last char in string */
   while(i-- > 0) {
      int rem = count % 26;
      count /= 26;
      *next-- = rem + 'A';   /*pntr positioned on 1 before array on last iteration - is OK? */
   }
}

int main(int argc, char* argv[])
{
   int buffsize = 5;
   char* buff = (char*)malloc(buffsize+1);

   strcpy(buff, "AAAAA");
   int iterations = 100;

   while(--iterations){
      getNextString(buff, buff);
      printf("iteration: %d buffer: %s\n", iterations, buff);
   }

   free(buff);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*xCQ 7

根据以下C-FAQ 问题\答案,我引用:

只要指针指向同一个分配的内存块,或者指向一个经过它的假想的"终止"元素,就只定义指针算术; 否则,即使指针未被解除引用,行为也是未定义的.

所以我的答案是否定的,在数组开始之前迭代是不行的.

还有对C标准的引用:

  • K&R2 Sec.5.3 p.100,Sec.5.4 pp.102-3,Sec.A7.7 pp.205-6
  • ISO秒 6.3.6(C89)或6.5.6/8(C99)
  • 基本原理 3.2.2.3