c segfault当修改数组值时
我在将DNA [i]更改为u时会得到一个segfault,我仍然不明白为什么。
另外,我正在用strCMP比较t的位置的值,但是据我了解,这是字符串文字的内容,我可以将其与dna [i] =='t'
进行比较。那对吗?谢谢。
#include <string.h>
char *dna_to_rna(char *dna) {
int size = (int)( sizeof(dna) / sizeof(dna[0]));
char *retour[size];
strcpy(retour, dna);
for (int i = 0; i < size; i++) {
if (dna[i] == 'T') {
dna[i] = 'U';
}
}
return (char *) retour;
}
int main() {
char *dna[] = {
"TTTT",
"GCAT",
"GACCGCCGCC"
};
char *actual, *expected;
size_t n;
for (n = 0; n < 3; ++n) {
actual = dna_to_rna(*(dna + n));
}
return 0;
}
Im getting a segfault when changing dna[i] to U, Ive debbuged but I still cant understand why.
Also I was comparing the value at a position against T with strcmp, but from what I understand thats for string literals and I can simply compare it with dna[i] == 'T'
. Is that right? thanks.
#include <string.h>
char *dna_to_rna(char *dna) {
int size = (int)( sizeof(dna) / sizeof(dna[0]));
char *retour[size];
strcpy(retour, dna);
for (int i = 0; i < size; i++) {
if (dna[i] == 'T') {
dna[i] = 'U';
}
}
return (char *) retour;
}
int main() {
char *dna[] = {
"TTTT",
"GCAT",
"GACCGCCGCC"
};
char *actual, *expected;
size_t n;
for (n = 0; n < 3; ++n) {
actual = dna_to_rna(*(dna + n));
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将传递到函数
dna_to_rna
指向字符串字面的指针,然后在函数中您试图更改字符串字面的
任何尝试更改字符串字面的尝试中的字符字面结果。
同样,在此声明中使用
sizeof
运算符的表达式也没有意义。它评估了类型
char *
的指针的大小。相反,您应该使用标准字符串函数
strlen
。而且该声明
至少是不正确的,您需要一个字符阵列而不是一系列指针。
该功能将返回一个带有自动存储持续时间的数组的指针,该数组退出功能返回函数返回无效指针后将不会活着
。
您应该在函数中动态分配一个字符数组,其中长度
strlen(dna) + 1
并更改并返回此数组。看来您的意思是如下
You are passing to the function
dna_to_rna
a pointer to a string literaland then within the function you are trying to change the string literal
Any attempt to change a string literal results in undefined behavior.
Also the expression with the
sizeof
operator in this declarationdoes not make a sense. It evaluates the size of a pointer of the type
char *
.Instead you should use the standard string function
strlen
.And this declaration is incorrect
At least you need a character array instead of an array of pointers.
And the function returns a pointer to an array with automatic storage duration that will not be alive after exiting the function
that is the function returns an invalid pointer.
You should dynamically allocate a character array within the function with the length
strlen( dna ) + 1
and change and return this array.It seems what you mean is something like the following