【发布时间】:2014-04-29 12:52:37
【问题描述】:
我已经把头撞到墙上了太多小时了,我需要你的帮助。在我的作业中,我应该编写一个函数,将字符串拆分为由空格分隔的标记。这些标记被复制到动态分配的字符串数组中。字符串作为参数传递,第二个参数是指向字符串数组的指针变量(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;
}
Valgrind 给出这个输出:
==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.
我一遍又一遍地阅读有关指针、字符串、数组和多维数组的内容,但我似乎无法掌握它。我真的不明白的一件事是,为什么将指针作为 (&args) 传递,为什么不将它作为数组指针传递?我也不确定我是否正确使用 memcpy。
【问题讨论】:
-
既然这是作业,我给你一个提示。函数声明可以是
int parse_cmdline(char **argv, const char* input)。根据此,尝试逆向工程传递的参数如何? -
Sizeof() 没有给出字符串的长度。我想你想要 strlen()
-
@Mahesh:你如何建议他用那个签名更新
args?
标签: c pointers command-line multidimensional-array argument-passing