【发布时间】:2017-12-14 22:24:50
【问题描述】:
我已经进行了很多挖掘,但似乎找不到与我遇到的问题类似的问题。
我通过一个函数传递一个字符串,该函数被放入一个 char 数组中,然后它查看这个 char 数组以查看第一个非十进制值在哪里,并将一个空字符放在那里。它通过将数组的值与 0-9 的 ascii 进行比较来做到这一点。 我的源代码给了我一个分段错误,但是如果我通过主要功能运行所有内容,它可以正常工作并且我的结果是否符合预期?有任何想法吗?我的源代码在下面
#include <string.h>
#include <stdio.h>
int try_null (char []); //function prototype
int main ()
{
printf("length is %d\n", try_null("123.txt"));
//This part doesn't give me a segmentation fault
/*char a [10];
strcpy(a, "123.txt");
int counter = 0, length = strlen(a);
for (counter = 0; counter < length; ++counter)
{
if ( (a[counter] >= 48) && (a[counter] <= 57) ); //if the value is a decimal leave it
else
a[counter]='\0'; //replace the first non decimal value with a null
}
length=strlen(a);
printf("%d\n", length); */
}
try_null(char value [10])
{
int counter, length = strlen(value); //find the current length of the array
printf("value is %d\n", length);
for (counter = 0; counter < length; ++counter)
printf("value is %c\n", value[counter]);
//getting rid of non-decimals
for (counter = 0; counter < length; ++counter)
{
if ( (value[counter] >= 48) && (value[counter] <= 57) ); //if the value is a decimal leave it
else
{
value[counter]='\0'; //replace the first non decimal value with a null
}
}
length=strlen(value);
return length;
}
【问题讨论】:
-
您尝试写入字符串文字,但不应这样做。如果你给出一个初始化的、以空结尾的、非常量的字符数组作为参数,你应该没有问题。
-
@bahjat 正确的感谢是接受或支持有用的答案!到目前为止,您已经就 SO 提出了 9 个问题。你没有接受一个...
-
@sg7 你的评论对我来说很受欢迎,我会检查我以前的问题并接受他们的答案:)
标签: c arrays function segmentation-fault