C语言 递增指针位置



我有一个字符指针,用于CSV文件的部分文件名。 我需要让它遵循以下模式:0, 1, 2, ..., 9, A, B, ..., Y, Z, 10, 11, ...等等永远。以下代码是处理程序中处理该问题的部分,但是当我尝试增加字符指针FILE_num中的一个"数字"时,我遇到了分割错误。我很确定我现在那里的内容将指针递增到下一个地址(不存在)。

我尝试了许多不起作用的东西(其中一半做同样的事情,另一半不编译)。这可能是其他失败的东西,但我相当确定就是这样。不幸的是,我必须使用 C,所以我不能使用字符串。

char * FILE_num ;
//
// from earlier in the program
//
FILE_num = (char *) malloc (sizeof (char)) ;
FILE_num = "0" ;
//
// skip several things that work but do not relate (maybe)
//
int lines = 0 ,
digit     ;
//
// some code that counts lines in a file
//
if (lines > 0xfffff) { // if file is too large start new file
for (digit = strlen (FILE_num) ; digit >= 0 ; digit --) {
if (FILE_num [digit] == 'Z') { // add to proper digit
FILE_num [digit] = '0' ;
}
else if (FILE_num [digit] == '9') { // skip :;<=>?@
FILE_num [digit] = 'A' ;
break ;
}
else {
FILE_num [digit] ++ ; // segmentation fault here
break ;
}
}
//
// Some other code to handle overflow of digits
//
}

您有内存泄漏和未定义的行为。

FILE_num = "0" ;

导致内存泄漏 - 丢失了动态分配的内存的地址。

"0"是一个包含字符'0'的数组。当你写这个语句时 - 该数组衰减为指向数组第一个元素的指针,然后你分配它。 前面FILE_num包含已分配内存的地址。现在你没有那个(根据你给出的代码- 如果你没有将地址存储在其他地方。所以你无法访问它。这就是为什么它是内存泄漏。

C 中的字符串文本是不可变的。你试图改变它。这是未定义的行为。

再一次,

FILE_num = (char *) malloc (sizeof (char)) ;

正在为1char分配内存。应分配适当大小的内存。如果要分配的大小1,则最好仅使用char(此处不是这种情况)。

digit = strlen (FILE_num);...

在这里,您首先访问- 这是不需要的。您可以从strlen( FILE_NUM )-1循环到0

而且malloc返回的void*被隐式转换为char*- 你不需要强制转换它。

所以正确的方法是

FILE_num = malloc (sizeof (char) * LENGTH) ;

您需要检查malloc的返回值,以便在失败时处理这种情况。

if( NULL == FILE_num ){
perror("malloc failed");
exit(EXIT_FAILURE);
}

此外,您跳过skip :;<=>?@的想法也不是那么清楚。您可能需要正确重新检查逻辑。


FILE_num = malloc(..)
char *store_for_later_use = FILE_num;
...

现在您可以更改FILE_num.

如果要使用与"0"使用strdup具有相同内容的字符串初始化FILE_num(如果不存在(不是标准的一部分),则可以将其("0")复制到动态分配的内存中)。

FIL_num = strdup("0");

请注意,使用完动态分配的内存后,释放它。 (您还需要释放strdup返回的内存的地址)。

最新更新