java定义动态string数组_如何为C中的字符串数组动态分配内存?

第一个malloc是错的..甚至'll you get when you derefer cmd by *cmd, before it'甚至分配了什么?

它也使用sizeof(char),这是错误的..

正确的方式是......

// strtok modifies the string. So use writable string

char line[80] = "Hello my name is anand";

char *token = strtok(line, sep);

int count = 0;

// Alloc array of char* for total number of tokens we have right now

char **cmds = (char **) malloc(sizeof(char*) * (count + 1));

while (token != NULL)

{

/**

* Alloc memory for the actual token to be stored..

* token returned by strtok is just reference to the existing string

* in 'line'

*/

cmds[count] = malloc(sizeof(char) * ((strlen(token) + 1)));

// Adds tokens to array of delimited commands

strcpy(cmds[count], token);

count++;

token = strtok(NULL, sep);

if (token != NULL)

{

// resize array of tokens to store an extra token

char ** newCmds = (char **) realloc(cmds, sizeof(char*) * (count + 1));

// only if realloc was successful then use it.

if (newCmds != NULL)

{

cmds = newCmds;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值