c - 如何获取我有指针指向的数组的位置?

标签 c ubuntu

我一直在尝试做这个指针练习,但我似乎没有发现我的错误。
练习包括编写一个函数来打印名称数组的信息,我想要位置、每个名称的长度和名称的字符串。您还应该知道 startPos 指向数组名称中每个 Name 开始的位置。 Description of arrays in the exercise

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 应该给我数组中名字所在的位置。例如,如果我有一个数组 Asterix\0Obelix\0\0\0\0... 那应该为我返回 00 为 Asterix 和 08 为 Obelix。问题是,当我尝试打印数组中的位置和长度时,它们都工作不正确。这是我编译它时得到的:
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;
}
输出:
startPos[0]=0 length=2 string="Ab"
startPos[1]=3 length=1 string="B"
startPos[2]=5 length=1 string="C"
应该够清楚,否则我可以解释更多。

关于c - 如何获取我有指针指向的数组的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69344503/

相关文章:

c - 如何将新的源文件添加到 glibc makefile 中?

c - "rand()% 11"是什么以及这和 "rand()% 10+1"之间有什么区别?

ubuntu - Docker - 无法连接到 Docker 守护进程

bash - 使用文件名的前 4 个字符创建唯一列表

c++ - 在 Ubuntu : "Invalid or incomplete multibyte or wide character", 和有趣的 UTF-8 字符上执行编译文件

C - 大端结构与小端结构相互转换

c - 以相反顺序打印文本文件中的行

c - 如何找到缓存友好代码中的未命中率?

python - PAM audit_log_acct_message() 失败 : Operation not permitted & User auth fails

c# - .NET 中的 HttpWebRequest NameResolutionFailure 异常(在 Ubuntu 上使用 Mono)