C字符串问题
我做了这个函数:
char** parse_cmd(const char* cmdline) {
int i;
int j = 0 ,k = 0;
char ch[100][100];
for(i=0; i<strlen(cmdline); i++) {
if(cmdline[i] != ' ') {
ch[j][k] = cmdline[i];
k++;
} else {
j++;
k = 0;
}
}
return ch;
}
但是当我编译程序时我有这个警告:
shell.c: In function ‘parse_cmd’:
shell.c:25:2: warning: return from incompatible pointer type
shell.c:25:2: warning: function returns address of local variable
为什么?
I made this function:
char** parse_cmd(const char* cmdline) {
int i;
int j = 0 ,k = 0;
char ch[100][100];
for(i=0; i<strlen(cmdline); i++) {
if(cmdline[i] != ' ') {
ch[j][k] = cmdline[i];
k++;
} else {
j++;
k = 0;
}
}
return ch;
}
But when I compile the program I have this warning:
shell.c: In function ‘parse_cmd’:
shell.c:25:2: warning: return from incompatible pointer type
shell.c:25:2: warning: function returns address of local variable
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试返回一个指向函数返回后不会与数组关联的内存位置的指针。如果您想永久分配内存,则必须在返回之前使用 malloc(或任何类似函数)复制它。
例如:
编辑:修复拼写错误。谢谢
You try to return a pointer to a memory location that will not be associated with the array after the function returned. If you want to permanently allocate the memory, then you have to copy it with
malloc
(or any similar function) before returning it.e.g:
EDIT: fixed typo. Thanx
您将返回一个指向堆栈上内存的指针。请改用堆分配的内存。
You're returning a pointer to memory that lives on the stack. Use heap allocated memory instead.
ch 数组在函数结束时被释放,该内存存储在堆栈上,该堆栈在函数返回后无效。您应该在调用函数中创建一个数组并将指针传递到 parse_cmd() 函数中。
The ch array is deallocated at the end of the function, that memory is stored on the stack which is invalid after the function returns. You should instead create a array in the calling function and pass the pointer into the parse_cmd() function.