将数组返回到C中的函数的问题
我的问题是我无法将处理的字符串返回到该功能。该函数的作业是它必须接受字符串,更改字母并将处理的字符串返回到该功能。
char *dna_strand(const char *dna)
{
int a;
for (a = 1; *(dna+a) != '\0' ; a++) {
}
char array[a];
for (int i = 0; i < a; ++i) {
if ('A' == *(dna + i)) {
array[i] = 'T';
} else if ('T' == *(dna + i)){
array[i] = 'A';
} else{
array[i] = *(dna + i);
}
}
return array;
}
错误 : [1]: https://i.sstatic.net/uwvch.png
My problem is that I can't return the processed string to the function. The function's job is that it must accept a string, change its letters, and return the processed string to the function.
char *dna_strand(const char *dna)
{
int a;
for (a = 1; *(dna+a) != '\0' ; a++) {
}
char array[a];
for (int i = 0; i < a; ++i) {
if ('A' == *(dna + i)) {
array[i] = 'T';
} else if ('T' == *(dna + i)){
array[i] = 'A';
} else{
array[i] = *(dna + i);
}
}
return array;
}
Error :
[1]: https://i.sstatic.net/uwvCh.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
本地变量
char数组[a];
不在呼叫者的范围内,因此您不能使用它来返回值。而是用malloc()
或此处分配内存 strdup():如果您想幻想使用
strpbrk()
查找我们需要映射的下一个字母,而不是一次踩一封信:The local variable
char array[a];
is out of scope for caller so you cannot use that to return a value. Instead allocate memory on the heap withmalloc()
or as herestrdup()
:If you want to be fancy use
strpbrk()
to find the next letter we need to map instead of stepping one letter at a time:您不得将指针返回具有自动存储持续时间的本地数组,因为退出功能后,数组将不会活着,并且返回的指针将无效。
您需要动态分配数组。
请注意此循环
当用户将一个空字符串传递给函数时,
可以调用不确定的行为。您至少应该写作
或
之后写一个字符数组的分配
You may not return a pointer to a local array with automatic storage duration because after exiting the function the array will not be alive and the returned pointer will be invalid.
You need to allocate an array dynamically.
Pay attention to that this loop
can invoke undefined behavior when the user will pass to the function an empty string.
You should write at least like
or
After that you can allocate dynamically a character array
您无法将指针返回到本地变量的地址,因为它将在函数范围中删除时会被破坏。
由于,
a
不是一个常数值,因此您不能初始化array
作为static
。因此,唯一的选项是使用 heap-Alocation 。
a
可以像这样初始化:注意:
calloc()
是在stdlib.h
标题文件中定义的。You cannot return a pointer to a local variable's address, because it will be destroyed when it will goes out from the function's scope.
Since,
a
is not a constant value, you cannot initializearray
asstatic
.Hence, the only option is left is using heap-allocation.
a
can be initialize like this:Note:
calloc()
is defined instdlib.h
header file.