访问结构中二维数组中一行的最后一个元素

Accessing the last element on a row in a 2D array that is in a structure

我正在尝试访问结构内二维数组每一行的最后一个元素。我正在尝试确定特定字符是否位于该位置,但我不知道如何访问该特定元素。

我的未完成代码:

typedef struct node {
   char grid[MAXGRIDHW][MAXGRIDHW];
   int height;
   int width;
   int parent;
} Node;

bool emptyEnd (Node *b)
{
   int x, y;
   char lastEle = ;

   for (y = 0; y <= b->height; y++) {
      for (x = 0; x <= b->width; x++) {
         if (lastEle == '-') {
            return true;
         } else {
            return false;
         }
      }
   }
}

试试这个:

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXGRIDHW 4

typedef struct node {
   char grid[MAXGRIDHW][MAXGRIDHW];
   int height;
   int width;
   int parent;
} Node;

_Bool emptyEnd (Node *b)
{
   int x, y;
   char lastEle = b->grid[MAXGRIDHW-1][MAXGRIDHW-1];
   printf("%c\n", lastEle);  //====> 'p'
   return (lastEle == '-');  
}

int main() {
    struct node n = { .height = 100, .width  = 100 };
    char grid[MAXGRIDHW][MAXGRIDHW] = {{'a', 'b', 'c', 'd'},
                                      {'e', 'f', 'g', 'h'},
                                      {'i', 'j', 'k', 'l'},
                                      {'m', 'n', 'o', 'p'}};
    memcpy(n.grid, grid, sizeof(char) * MAXGRIDHW * MAXGRIDHW);
    printf("%d\n", emptyEnd(&n)); //===> false
}

struct 中是否存在二维数组真的很重要吗?

如果稍加修改就可以使下面的程序正常工作。

不传递结构变量,而是传递结构内部的数组。

希望以下内容能满足您的要求。

#define MAX_NUM_OF_LINES 3
#define MAX_NUM_OF_CHARS_PER_LINE 15

bool getTheLastChar(char *str);

int main()
{
    char Arr[MAX_NUM_OF_LINES][MAX_NUM_OF_CHARS_PER_LINE] = {"ABC-","DEFG","HIJ-"};
    int i;
    for(i = 0; i<MAX_NUM_OF_LINES; i++)
    {
        if(true == getTheLastChar(Arr[i]))
            printf("there is a - at last in %s\n", Arr[i]);
    }
   return 0;
}

bool getTheLastChar(char *str)
{
    bool retVal = false;
     
    if( str[strlen(str)-1] == '-')
       retVal = true;
     
    return retVal;
}

如评论中所述:

  • 在 C 中,for 循环通常是 运行 for (int i = 0; i < limit; i++) 这样数组的 limit 元素都可以被访问而不会超出数组的边界(这会导致未定义的行为)。

  • 记住,如果你有一个数组 SomeType array[10];,有效索引的值为 0..9; array[10] 不是您可以合法访问的元素(尽管您可以形成地址 &array[10] 并与之进行比较)。

  • 您的 lastEle 代码无效 C.

  • 鉴于“如果最后一列值中的任何一个与指定的字符匹配,函数应该 return true”的要求,你的双循环是不必要的。每行只需检查一个字符,因此遍历行数就足够了。

  • 原始代码无条件地 return 来自内循环第一次迭代的函数在外循环的第一次迭代中——使循环完全不必要。您需要保留 return true; 并完全删除 else 子句,在循环体之后添加 return false;

  • 原代码中的内循环是不需要的。每行只有最后一个字符,因此无需为行中的每个字符位置检查该行的最后一个字符是否匹配固定值。

这是有效的代码。它不假定网格由字符串组成——字节 (char) 数组不一定以 null 结尾。它不假设网格最大程度地充满(heightwidth 或两者都可以小于 MAXGRIDHW)。搜索函数由要搜索的字符参数化,以便可以测试代码搜索不同的字符。我保留了结构的 parent 元素,尽管它在代码中没有发挥任何作用。我使用了 C99 指定的初始值设定项和 C99 风格的 for 循环,其中循环变量在循环控件中定义。我包含了 print_grid() 函数,因为我希望能够看到搜索是正确的。

#include <stdbool.h>
#include <stdio.h>

enum { MAXGRIDHW = 6 };

typedef struct node
{
    char grid[MAXGRIDHW][MAXGRIDHW];
    int height;
    int width;
    int parent;
} Node;

static bool emptyEnd(Node *b, char c)
{
    for (int y = 0; y < b->height; y++)
    {
        if (b->grid[y][b->width - 1] == c)
            return true;
    }
    return false;
}

static void print_grid(const char *tag, const Node *np)
{
    printf("%s: P = %d, H = %d, W = %d\n", tag, np->parent, np->height, np->width);
    for (int r = 0; r < np->height; r++)
    {
        for (int c = 0; c < np->width; c++)
            putchar(np->grid[r][c]);
        putchar('\n');
    }
}

int main(void)
{
    Node n =
    {
        .parent = 0, .width = 5, .height = 4,
        .grid =
        {
            { 'a', 'b', 'c', 'd', 'e' },
            { 'b', 'c', 'd', 'x', 'z' },
            { 'p', 'p', '*', '*', '-' },
            { '@', '@', '@', '!', '-' },
        },
    };
    char test[] = "-eA";

    print_grid("Test Grid", &n);

    for (int i = 0; test[i] != '[=10=]'; i++)
    {
        if (emptyEnd(&n, test[i]))
            printf("At least one last character is '%c'\n", test[i]);
        else
            printf("Not even one last character is '%c'\n", test[i]);
    }
    return 0;
}

程序的输出是:

Test Grid: P = 0, H = 4, W = 5
abcde
bcdxz
pp**-
@@@!-
At least one last character is '-'
At least one last character is 'e'
Not even one last character is 'A'