我有这三个文件 main.h、4-main.c 和 4-print_rev.c,这三个文件都需要反向打印字符串。 我不允许使用标准库,因此不使用 strlen() 或 printf() 的原因是我必须使用 _putchar() 执行与 putchar() 相同的操作
但是,当我在我的 Linux 沙箱上编译和运行时,出现分段错误(核心转储)错误。 我使用了一个在线编译器,它工作正常。请帮助。
main.h
#define MAIN_H
#include <stdio.h>
#include <stdlib.h>
int _putchar(char c);
void reset_to_98(int *n);
void swap_int( int *a, int *b);
int _strlen(char *s);
void _puts(char *s);
void print_rev(char *s);
#endif
4-main.c
#include "main.h"
/**
* main - check the code
*
* Return: Always 0.
*/
int main(void)
{
char *str;
str = "I do not fear computers. I fear the lack of them - Isaac Asimov";
print_rev(str);
return (0);
}
4-print_rev.c
#include "main.h"
/**
* print_rev - prints a string
* @s: the string to be printed
*/
void print_rev(char *s)
{
int i;
while (s[i] != '\0')
{
i++;
}
while (i > 0)
{
_putchar(s[i-1]);
i--;
}
_putchar('\n');
}
我意识到没有将我的迭代器 i 初始化为 0 是分段错误的原因。
所以我将我的 4-print_rev.c 更新为这个,我很高兴。 再次感谢@Vlad
#include "main.h"
/**
* print_rev - prints a string
* @s: the string to be printed
*/
void print_rev(char *s)
{
int i = 0;
while (s[i] != '\0')
{
i++;
}
while (i > 0)
{
_putchar(s[i-1]);
i--;
}
_putchar('\n');
}