我正在尝试编写一个程序,该程序将使用任意数字并将位翻转并加一个,并且我已经编写了代码,但是我一直遇到分段错误(核心转储)错误。有人可以看一下我的代码,看看为什么会发生此错误。我在下面附加了我的代码以及我想接收的输入和输出。
#include "stdio.h"
#include "malloc.h" //Needed for malloc, realloc, and free
#define GROW_BY 2
#define MAX_BITS 32
int add_one(int in_array[], int num){
for (int i = 0; in_array[i] != NULL; i++) {
int add_one = in_array[num - i] + 1;
}
return add_one;
}
int main() {
//Declaration and Initialization of Variables
int* array = NULL;
int bit = getchar();
int count = 0;
while (bit != '\n') {
bit = bit - '0';
*array = &bit;
array = (int*)malloc((strlen(bit) + 1) * sizeof(int));
if (array == NULL) {
printf("An error has occurred and the program will now $
return 1;
}
bit = getchar();
}
for (int j = count - 1; j >= 1; j--) {
if (array[j] == '1') {
array = (int*)realloc(array, GROW_BY * sizeof(int));
if (array == NULL) {
printf("An error has occurred and the program w$
}
}
else if (array[j] == '0' ) {
array = (int*)realloc(array, GROW_BY * sizeof(int));
if (array == NULL) {
printf("An error has occurred and the program w$
return 1;
}
}
}
add_one(array, bit);
for (int j = count - 1; j >= 1; j--) {
if (array[j] == '1' && add_one == 1) {
array[j] = '0';
}
else if (array[j] == '0' && add_one == 1) {
array[j] = '1';
int add_one = 0;
}
else {
array[j] = array[j];
}
}
printf("%ls/n", array);
free(array);
return 0;
}
Input: 101011110
Output: 010100010