Home > Net >  Best Practice for pointers in C-language
Best Practice for pointers in C-language

Time:04-17

I am new to C. So here's my question. Is it consider a bad practice to use negative index when using a pointer?

consider the following code:

#include <stdio.h>
void loopDown(int *intPointer, int maxStep);
int main() {
    int myArray [10]={0};
    myArray[0] = 5;
    int myMaxStep = 5;
    int *myPointer = myArray   myMaxStep;
    
    // loopDown(&*myPointer,myMaxStep); //Bad practice suggested by Jonathan
    loopDown(myPointer,myMaxStep); //Edited version
    
    return 0;
}

void loopDown(int *intPointer, int maxStep){
  int i;
  int j;
  
  for(i=0;i<=maxStep;i  ){
    //   printf("%d",i);
      j = -1*i;
      printf("%d\n",intPointer[j]);
  }
};

and it's output:

0
0
0
0
0
5

unlike python(another language that I use), c doesn't have a quick way to slice an array. And I think pointer is a very convenient solution for me to "cut" the array without actually cutting it. Would this be consider hard to read/bad practice or have a better situation to it?

if there is other bad practice in other portion of the code feel free to point it out. I am still learning. Thanks :)

CodePudding user response:

The computer does not care. The compiler does not care. The C standard defines semantics for negative offsets from pointers. Programs using them correctly will work as desired.

So the only consideration is humans. Humans are trouble. They misunderstand things, they make mistakes. They develop habits, they make assumptions. Some of them may assume “array indices” are nonnegative, even though nothing in the C standard says so.

It is fine to use negative pointers, but make sure the error-prone humans know what you are doing. Sometimes negative indices arise naturally. There are signal filters that are compute the next new output as a function of some inputs and a few previous outputs. In this case, when OutputPointer is pointing to the place where the next output should be stored, the previous outputs are naturally OutputPointer[-1], OutputPointer[-2], and so on.

All source code should be well documented, regardless of whether it uses negative offsets or not. Make it clear to the reader what the software is doing and why.

  • Related