Home > Mobile >  How to get the possition of an array to which I have a pointer pointing?
How to get the possition of an array to which I have a pointer pointing?

Time:09-27

I have been trying to do this pointer excercise but I dont seem to find my error. The exercise consists on writing a function to print the information of an array of names, I want the position, the length of each name and the string of the name. You should also know that startPos points to the position in the array names to which each Name starts. Description of arrays in the exercise

void printNames(char names[], char *startPos[], int nrNames){
  
  for(int i = 0; i < nrNames; i  ){
    printf("startPos[%d]=d length=d string=%c%s%c\n",i , names[*startPos[i]],
     names[*startPos[i 1]]-names[*startPos[i]],'"', startPos[i],'"');
  }
}

The first d is suposed to give me the position in my array where the first name is. So for example if i have an array Asterix\0Obelix\0\0\0\0... that should return me 00 for Asterix and 08 for Obelix. The thing is, when I try to print the position in the array and the length they both work incorectly. This is what I get when i compile it: output As you can see, the output doesn't make sense because the positions shoud change and the length should be the number of characters each name has the \0 char. I have tried so many different ways to fix it but none of them work. Hope somebody can help me with it. Thanks in advance.

CodePudding user response:

This should help you:

#include <stdio.h> // printf()
#include <string.h> // strlen()
#include <stddef.h> // ptrdiff_t, size_t

void printNames(char names[], char *startPos[], int nrNames) {
    for (int i = 0; i < nrNames; i  = 1) {
        // let's calculate the position of `startPos[i]` inside `names`
        // NOTE: ptrdiff_t is the usual type for the result of pointer subtraction
        ptrdiff_t pos = (ptrdiff_t) (startPos[i] - names);
        // let's calculate the length the usual way
        size_t len = strlen(startPos[i]);

        // NOTE: %td is used to print variables of type `ptrdiff_t`
        printf("startPos[%d]=%td length=%zu string=\"%s\"\n", i, pos, len, startPos[i]);
    }
}

int main(void) {
    char names[] = "Ab\0B\0C\0\0";
    char* startPos[3];

    startPos[0] = &names[0];
    startPos[1] = &names[3];
    startPos[2] = &names[5];

    printNames(names, startPos, 3);

    return 0;
}

Output:

startPos[0]=0 length=2 string="Ab"
startPos[1]=3 length=1 string="B"
startPos[2]=5 length=1 string="C"

It should be clear enough, otherwise I may explain more.

  • Related