使用2D动态分配的字符串创建动态分配的结构 [英] Creating a dynamically allocated struct with a 2D dynamically allocated string

查看:101
本文介绍了使用2D动态分配的字符串创建动态分配的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母网格进行扫描. cases是字母网格的数量,rc是每个网格的行数和列数.我以为我可以创建一个带有2D数组的结构数组.我已经为此工作了几个小时,但仍然给我带来了问题:

I'm trying to scan in a grid of letters. cases is the number of letter grids and r, c are for number of rows and columns of each grid. I figured I could create an array of structs with 2D arrays inside. I've been working on this for a few hours now and it's still giving me problems:

  • 警告:

  • Warnings:

  • 警告C4477 (第12行)-'scanf_s':格式字符串'%s'需要类型为'char *'的参数,而可变参数1的类型为'int'
  • 警告C4473 (第12行)-"scanf_s":没有为格式字符串传递足够的参数
  • Warning C4477 (Line 12) - ‘scanf_s’ : format string ‘%s’ requires an argument of type ‘char*’, but variadic argument 1 has type ‘int’
  • Warning C4473 (Line 12) - ‘scanf_s’ : not enough arguments passed for format string

错误:

编译器错误C2461

代码:

scanf_s("%d", &cases);
struct grid { 
    char **grid; 
};
struct grid *grids = (struct grid*)malloc(cases * sizeof(struct grid));

for (i = 0; i < cases; i++) {
    scanf_s("%d %d", &r, &c);
    grids[i].grid = (char**)malloc(sizeof(char*) * r);
    for (k = 0; k < r; k++) {
        grids[i].grid[k] = (char*)malloc(sizeof(char) * (c+1));
        scanf_s("%s", grids[i].grid[k], (c+1));
    }           
}

推荐答案

我不得不微调问题中的代码,还添加了一些遗漏的部分(应该提供,btw),以获得一个可编译(使用 VStudio2010 ).

I had to tweak a little bit the code in the question, also to add some missing parts (that should have also been provided, btw), to get a compilable (using VStudio2010) piece.

main00.c :

#include <stdio.h>
#include <stdlib.h>


struct grid { 
    char **grid; 
};


int main() {
    int cases, r, c, k, i;
    struct grid *grids;

    scanf_s("%d", &cases);
    grids = (struct grid*)malloc(cases * sizeof(struct grid));

    for (i = 0; i < cases; i++) {
        scanf_s("%d %d", &r, &c);
        grids[i].grid = (char**)malloc(sizeof(char*) * r);
        for (k = 0; k < r; k++) {
            grids[i].grid[k] = (char*)malloc(sizeof(char) * (c + 1));
            scanf_s("%s", grids[i].grid[k], (c + 1));
        }           
    }
    return 0;
}

注释:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆