使用2D动态分配的字符串创建动态分配的结构 [英] Creating a dynamically allocated struct with a 2D dynamically allocated string
本文介绍了使用2D动态分配的字符串创建动态分配的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按字母网格进行扫描. cases
是字母网格的数量,r
,c
是每个网格的行数和列数.我以为我可以创建一个带有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
错误:
代码:
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;
}
注释:
- 您正在将代码编译为 C ++ (如@alk所示),这完全使您偏离了路线.为了解决这个问题,请执行以下操作:
- 将文件扩展名设置为 .c (您可以在编译时保留 VStudio 默认值;这样,它将使用基于在其扩展名上)
- 明确地将源文件编译为 C .您可以通过 VStudio项目属性-> C/C ++->高级->编译为进行设置,然后选择编译为C代码.有关更多信息,请访问
- You were compiling the code as C++ (as @alk noticed), and this is what completely threw you off course. In order to fix that either:
- Set your file extension to .c (and you can leave the VStudio defaults in term of compilation; that way it will compile each source file using the appropriate compiler based on its extension)
- Explicitly compile the source file as C. You can set that from VStudio Project Properties -> C/C++ -> Advanced -> Compile As, and choosing Compile as C Code. For more info, visit [MS.Docs]: /Tc, /Tp, /TC, /TP (Specify Source File Type). Personally, I think that the former option is more straightforward
这篇关于使用2D动态分配的字符串创建动态分配的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文