【问题标题】:Function printing list of words功能打印单词列表
【发布时间】:2020-11-22 03:48:35
【问题描述】:

我试图了解这里出了什么问题。

void longestConsec(char* strarr[], int n) {
  for(int i=0; i<n; i++)
  {
    printf("%s\n",strarr[i]);
  }
}

int main()
{
    char string[8][14] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
    longestConsec(string, 8);
    return 0;
}

我想打印每个单词,但由于某种原因它不起作用。我想到的是strarr 是指向char 的指针数组,所以在每个单元格中都应该有一个单词,对吧?但是当我尝试调试代码时,我看到 strarr 和 strarr[0] 有不同的内存位置。为什么?

【问题讨论】:

  • “它不起作用”。你能解释一下你看到的输出吗?除非很明显,否则为什么输出是错误的?
  • 你怎么看出strarrstrarr[0]有不同的内存位置?
  • 阅读您的编译器警告。他们随时为您提供帮助。
  • 另外,你可以看看这里stackoverflow.com/q/1641957/6699433,因为数组和指针是不同的东西
  • @MikeCAT,我使用调试器中的监视窗口,我看到它们有不同的地址。

标签: arrays c string function pointers


【解决方案1】:

你的编译器应该给你一个警告,给你一个很好的提示。

k.c:12:19: warning: passing argument 1 of ‘longestConsec’ from incompatible pointer type [-Wincompatible-pointer-types]
   12 |     longestConsec(string, 8);
      |                   ^~~~~~
      |                   |
      |                   char (*)[14]
k.c:2:26: note: expected ‘char **’ but argument is of type ‘char (*)[14]’
    2 | void longestConsec(char* strarr[], int n) {
      |                    ~~~~~~^~~~~~~~

string 是一个数组数组,char[8][14]strarr 是指向 char 的指针,char **。当string 传递给函数时,它衰减为指向14 个字符数组的指针char (*)[14]。将多维数组传递给函数可能会很棘手,但这是可行的:

// size_t is better than int in this case
void longestConsec(size_t len, char strarr[][len], size_t n) 
{
    for(int i=0; i<n; i++)
        printf("%s\n",strarr[i]);
}

然后调用它:

longestConsec(sizeof string[0]/sizeof string[0][0], // 14
              string, 
              sizeof string/sizeof string[0]        // 8
              );

请注意,您可以写 sizeof string[0] 而不是 sizeof string[0]/sizeof string[0][0],但这是因为 sizeof char 始终为 1。

理解这些声明可能有点棘手。仅举一个类型示例说明它们是如何声明的:

char (*arr)[10]; // arr is a pointer to array of char of size 10
char *arr[10];   // arr is an array of 10 pointers to char

相关:arrays are not pointers and pointers are not arrays

【讨论】:

  • 哦,好的,谢谢。我会检查链接。现在我明白了这些警告。真的没想到它们这么有用。
  • @MihalacheRares 警告非常有用。它们解释了大多数错误。
【解决方案2】:

strarr 是一个指向 char 的指针数组,但 string 不是一个指针数组,而是一个 14 元素的 char 数组。

指针和 14 元素字符数组的大小可能不同,因此您的代码将无法正常运行。

像这样使用指针数组怎么样?

#include <stdio.h>

void longestConsec(const char* strarr[], int n) {
  for(int i=0; i<n; i++)
  {
    printf("%s\n",strarr[i]);
  }
}

int main()
{
    const char* string[8] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
    longestConsec(string, 8);
    return 0;
}

【讨论】:

  • strarr 不是指向 char 的指针数组。它是一个指向 char 的指针。
猜你喜欢
  • 2017-01-25
  • 2012-09-15
  • 2017-07-02
  • 2020-07-25
  • 2019-09-08
  • 2020-07-14
  • 2021-06-24
  • 2017-03-12
  • 1970-01-01
相关资源
最近更新 更多