簡體   English   中英

如何獲得指針指向的數組的位置?

[英]How to get the possition of an array to which I have a pointer pointing?

我一直在嘗試做這個指針練習,但我似乎沒有發現我的錯誤。 練習包括編寫一個 function 來打印名稱數組的信息,我想要 position、每個名稱的長度和名稱的字符串。 您還應該知道,startPos 指向每個 Name 開始的數組名稱中的 position。 練習中arrays的說明

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

第一個 %02d 應該給我數組中第一個名字所在的 position。 因此,例如,如果我有一個數組Asterix\0Obelix\0\0\0\0...應該為 Asterix 返回 00,為 Obelix 返回 08。 問題是,當我嘗試在數組中打印 position 和長度時,它們都無法正常工作。 這是我編譯時得到的: output如您所見,output 沒有意義,因為位置應該改變,長度應該是每個名稱具有的字符數 + \0 字符。 我嘗試了很多不同的方法來修復它,但都沒有用。 希望有人可以幫助我。 提前致謝。

這應該可以幫助您:

#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"

應該夠清楚了,否則我可能會解釋得更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM