- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我的头撞在墙上已经好几个小时了,我需要你的帮助。在我的作业中,我应该编写一个函数,将字符串拆分成用空格分隔的标记。这些令牌被复制到动态分配的字符串数组中。字符串作为参数传递,第二个参数是指向字符串数组的指针变量(char**argv)。我很难理解如何处理这个三维数组以及如何动态地分配它。以下是相关代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char **args = NULL;
char cmdline[] = "cmdline -s 20 -r -t parameter -p 20 filename";
int count = parse_cmdline(&args, cmdline);
#include <stdlib.h>
#include <string.h>
/* Parses a string into tokens (command line parameters) separated by space
* Builds a dynamically allocated array of strings. Pointer to the array is
* stored in variable pointed by argv.
*
* Parameters:
* argv: pointer to the variable that will store the string array
* input: the string to be parsed (the original string can be modified, if needed)
*
* Returns:
* number of space-separated tokens in the string */
int parse_cmdline(char ***argv, char *input)
{
int i=0;
char *token=strtok(input," ");
while (token!=NULL) {
*argv=realloc(*argv,(i+1)*sizeof(char*));
*argv[i]=malloc(sizeof(token));
memcpy(*argv[i],token,sizeof(token));
i++;
token=strtok(NULL," ");
}
return i;
}
==358== Use of uninitialised value of size 8
==358== at 0x40263B: parse_cmdline (cmdline.c:21)
==358== by 0x40155E: test_parse_cmdline (test_source.c:19)
==358== by 0x405670: srunner_run_all (in /tmc/test/test)
==358== by 0x40221E: tmc_run_tests (tmc-check.c:121)
==358== by 0x401ED7: main (test_source.c:133)
==358== Uninitialised value was created by a stack allocation
==358== at 0x401454: test_parse_cmdline (test_source.c:10)
==358==
==358== Invalid write of size 8
==358== at 0x40263B: parse_cmdline (cmdline.c:21)
==358== by 0x40155E: test_parse_cmdline (test_source.c:19)
==358== by 0x405670: srunner_run_all (in /tmc/test/test)
==358== by 0x40221E: tmc_run_tests (tmc-check.c:121)
==358== by 0x401ED7: main (test_source.c:133)
==358== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==358==
==358==
==358== Process terminating with default action of signal 11 (SIGSEGV)
==358== Access not within mapped region at address 0x0
==358== at 0x40263B: parse_cmdline (cmdline.c:21)
==358== by 0x40155E: test_parse_cmdline (test_source.c:19)
==358== by 0x405670: srunner_run_all (in /tmc/test/test)
==358== by 0x40221E: tmc_run_tests (tmc-check.c:121)
==358== by 0x401ED7: main (test_source.c:133)
==358== If you believe this happened as a result of a stack
==358== overflow in your program's main thread (unlikely but
==358== possible), you can try to increase the size of the
==358== main thread stack using the --main-stacksize= flag.
==358== The main thread stack size used in this run was 8388608.
最佳答案
除了使用sizeof
而不是strlen
之类的错误用法之外,让我们先看看其他几个问题。
为什么&args
?
有一件事我真的不明白,为什么指针是作为(&args)传递的,为什么不直接作为数组指针传递呢?
看看你的陈述:
char **args = NULL;
char **args
1. char args => args is char.
2. char *args => args is pointer to char.
3. char **args => args is pointer to pointer to char.
char **args = NULL;
args * *0x123e0a -> [0] 0x123fa00 -> 0x12fbae0 - 0x12fbae8 cmdline [1] 0x123fa08 -> 0x12fbae9 - 0x12fbaec -s [2] 0x123fa10 -> 0x12fcae0 - 0x12fcae3 20 [3] 0x123fa18 -> 0x12fbad8 - 0x12fbadb -r ...
If we look at a simpler variant first:
1. char args => args is char.
2. char *args => args is pointer to char.
3. char *args = NULL => args is pointer to char, pointing to NULL.
4. char *args = malloc(9); => args is pointer to char, pointing to some address.
returned by malloc().
args
和任何变量一样,在所有步骤中都有一个地址。你总是可以说:
printf("Address of args=%p\n", (void*)&args);
char **args = NULL
。
1. char **args;
2. char **args = NULL;
3. char **args = malloc(1);
4. char **args = malloc(1);
args[0] = malloc(9);
Address1. args: 0xabc00 /-> Nowhere /-> Nowhere2. args: 0xabc00 -> NULL /-> Nowhere3. args: 0xabc00 -> 0xcf324 /-> Nowhere4. args: 0xabc00 -> 0xcf324 -> 0xedf00 - 0xedf09
Now, if you want some function to manipulate what ever args point to what would you give to that function? You need to pass the address of what args point to.
What if you also want to change where it points as well as what it points to? You need to pass the address of the pointer itself. This so you can say: "args point here instead of there."
Again: As you do realloc() on args you need to update args with the new address to point to.
I'm having a hard time to understand how to handle this triple dimensional array and how to dynamically allocate it.
It is not a "triple dimensional array". It is a pointer to a pointer to a pointer. Or perhaps simpler in light of context: it is a pointer to a double pointer. Or pointer to a two dimensional array if you like.
char **args = NULL; | +-----> 0x123400 -> NULL parse_cmdline(&args, cmdline); | +-----> 0x123400 -> NULL
inside parse_cmdline():
int parse_cmdline(char ***argv, const char* cmd)
&argv => Address of the argument.
argv => 0x123400 (Same address as in main)
*argv => NULL (Points to NULL)
/* Inside loop: */
/* First round: */
*argv = realloc(*argv, (i + 1) * sizeof(char*));
| |
| +--------> Initial address NULL
+------------------------> Updated address 0x1234af
/* Second round */
*argv = realloc(*argv, (i + 1) * sizeof(char*));
| |
| +--------> Old address 0x1234af
+------------------------> Updated address 0x1234bd
/* ... */
0x123400
,但它不再指向NULL,而是指向最后一个realloc()的地址,例如
0x1234bd
。
ptr->args
与
args
printf("%s\n", args[0]);
printf("%s\n", args[1]);
*argv
*
取消对argv的引用以从main获取args。到现在为止,一直都还不错。但是你说:
*argv[i]
[]
。因此,您正在索引的是ARGV,而不是它指向的,然后您尝试取消引用索引的地址。类似于:
foo = argv[i];
*foo = malloc(...);
(*argv)[i] = malloc(...);
/* and */
memcpy((*argv)[i], token, strlen(token) + 1);
12 + 4 / 2
*
具有更高的优先级,您需要添加括号:
(12 + 4) / 2
/
没有给出字符串的长度。在你的代码中,它会给你一个字符指针的大小。如:指针的大小。
char foo[32] = "ab";
int bar[64];
char *baz;
sizeof foo => 32
sizeof bar => 64 * size of int e.g. 64 * 8 = 512
sizeof baz => 8 (or 4 or what ever the size of a pointer is in
current environment.)
memcpy((*argv)[i], token, strlen(token) + 1);
|
+----- Include 0x00 at end of token.
sizeof
替换分隔符,这样就不需要手动添加它了。这也是为什么可以使用strlen()的原因。如果不终止空值,除非事先知道长度,否则就没有可能。
0x00
帮助您。打印很多。打印字符串长度、变量大小等,在这种情况下打印地址。例如在main中:
printf("args=%p\n", (void*)&args);
printf()
而不是
args
,并努力做到这一点。同时尝试在函数中使用临时指针:
int parse_cmdline(char ***argv, char *input)
{
int i = 0;
char **argx = *argv; /* Temporary local. */
char *token = strtok(input, " ");
fprintf(stderr, "argv=%p\n", (void*)argv);
while (token != NULL) {
fprintf(stderr,
"%15s, sizeof=%u strlen=%u\n",
token, sizeof(token), strlen(token)
);
/* Now you can refer argx like you would args in main().
* as in: argx[i] instead of (*argv)[i] etc.
*/
}
/* Update pointer before return. */
*argv = argx;
return i;
}
关于c - 传递指针变量以存储字符串数组(命令行参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22570892/
猫f1.txt阿曼维沙尔阿杰贾伊维杰拉胡尔曼尼什肖比特批评塔夫林现在输出应该符合上面给定的条件 最佳答案 您可以在文件读取循环中设置一个计数器并打印它, 计数=0 读取行时做 让我们数一数++ if
我正在尝试查找文件 1 和文件 2 中的共同行。如果公共(public)行存在,我想写入文件 2 中的行,否则打印文件 1 中的非公共(public)行。fin1 和 fin2 是这里的文件句柄。它读
我有这个 SQL 脚本: CREATE TABLE `table_1` ( `IDTable_1` int(11) NOT NULL, PRIMARY KEY (`IDTable_1`) );
我有 512 行要插入到数据库中。我想知道提交多个插入内容是否比提交一个大插入内容有任何优势。例如 1x 512 行插入 -- INSERT INTO mydb.mytable (id, phonen
如何从用户中选择user_id,SUB(row, row - 1),其中user_id=@userid我的表用户,id 为 1、3、4、10、11、23...(不是++) --id---------u
我曾尝试四处寻找解决此问题的最佳方法,但我找不到此类问题的任何先前示例。 我正在构建一个基于超本地化的互联网购物中心,该区域分为大约 3000 个区域。每个区域包含大约 300 个项目。它们是相似的项
preg_match('|phpVersion = (.*)\n|',$wampConfFileContents,$result); $phpVersion = str_replace('"','',
我正在尝试创建一个正则表达式,使用“搜索并替换全部”删除 200 个 txt 文件的第一行和最后 10 行 我尝试 (\s*^(\h*\S.*)){10} 删除包含的前 10 行空白,但效果不佳。 最
下面的代码从数据库中获取我需要的信息,但没有打印出所有信息。首先,我知道它从表中获取了所有正确的信息,因为我已经在 sql Developer 中尝试过查询。 public static void m
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我试图在两个表中插入记录,但出现异常。您能帮我解决这个问题吗? 首先我尝试了下面的代码。 await _testRepository.InsertAsync(test); await _xyzRepo
这个基本的 bootstrap CSS 显示 1 行 4 列: Text Text Text
如果我想从表中检索前 10 行,我将使用以下代码: SELECT * FROM Persons LIMIT 10 我想知道的是如何检索前 10 个结果之后的 10 个结果。 如果我在下面执行这段代码,
今天我开始使用 JexcelApi 并遇到了这个:当您尝试从特定位置获取元素时,不是像您通常期望的那样使用sheet.getCell(row,col),而是使用sheet.getCell(col,ro
我正在尝试在我的网站上开发一个用户个人资料系统,其中包含用户之前发布的 3 个帖子。我可以让它选择前 3 条记录,但它只会显示其中一条。我是不是因为凌晨 2 点就想编码而变得愚蠢? query($q)
我在互联网上寻找答案,但找不到任何答案。 (我可能问错了?)我有一个看起来像这样的表: 我一直在使用查询: SELECT title, date, SUM(money) FROM payments W
我有以下查询,我想从数据库中获取 100 个项目,但 host_id 多次出现在 urls 表中,我想每个 host_id 从该表中最多获取 10 个唯一行。 select * from urls j
我的数据库表中有超过 500 行具有特定日期。 查询特定日期的行。 select * from msgtable where cdate='18/07/2012' 这将返回 500 行。 如何逐行查询
我想使用 sed 从某一行开始打印 n 行、跳过 n 行、打印 n 行等,直到文本文件结束。例如在第 4 行声明,打印 5-9,跳过 10-14,打印 15-19 等 来自文件 1 2 3 4 5 6
我目前正在执行验证过程来检查用户的旧密码,但问题是我无法理解为什么我的查询返回零行,而预期它有 1 行。另一件事是,即使我不将密码文本转换为 md5,哈希密码仍然得到正确的答案,但我不知道为什么会发生
我是一名优秀的程序员,十分优秀!