gpt4 book ai didi

c - 为什么我的 C 代码每次都不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 00:17:46 24 4
gpt4 key购买 nike

我编写这段代码是为了合并两个已排序的数组。期望的输出是:

Merged array:0 1 2 3 4 5 6 7 8 9 10 11 12

我正在使用 gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 来编译我的代码。

问题是有时我在执行 a.out 文件时会得到所需的输出,但在其他情况下,光标会一直闪烁并且没有显示任何结果。为什么会这样?我的代码有问题吗?

#include<stdio.h>
#include<stdlib.h>

int main(void){

//change arrays as per your need but it should be sorted
int a[] = {1,2,3,7,8};
int b[] = {0,3,5,6,9,10,11,12};

int m =sizeof(a) / sizeof(int);
int n =sizeof(b) / sizeof(int);

int index=0, j=0, k=0;
int size = m + n;
int array[size];


while(index < size) {

while(a[j] < b[k] && j<m ){
array[index] = a[j];
++index;
++j;
}
while(a[j] > b[k] && k<n){
array[index] = b[k];
++index;
++k;
}
while(a[j] == b[k]){
array[index] = a[j];
j++; index++;
}
}

printf("Merged array: ");
for(int i=0; i<size; i++)
printf("%d ", array[i]);

printf("\n");

}

最佳答案

您有未定义的行为(越界访问数组)。使用 gcc -fsanitize=undefined 创建一个可以检测各种不良行为的可执行文件。

% gcc -g fffff.c -Wall -Wextra -fsanitize=undefined
% ./a.out
fffff.c:20:12: runtime error: index 5 out of bounds for type 'int [5]'
fffff.c:20:12: runtime error: load of address 0x7ffd0c0c9804 with insufficient space for an object of type 'int'
0x7ffd0c0c9804: note: pointer points here
08 00 00 00 04 00 00 00 04 00 00 00 04 00 00 00 00 00 00 00 03 00 00 00 05 00 00 00 06 00 00 00
^
fffff.c:25:12: runtime error: index 5 out of bounds for type 'int [5]'
fffff.c:25:12: runtime error: load of address 0x7ffd0c0c9804 with insufficient space for an object of type 'int'
0x7ffd0c0c9804: note: pointer points here
08 00 00 00 04 00 00 00 04 00 00 00 04 00 00 00 00 00 00 00 03 00 00 00 05 00 00 00 06 00 00 00
^
fffff.c:30:12: runtime T: index 5 out of bounds for type 'int [5]'
fffff.c:30:12: runtime error: load of address 0x7ffd0c0c9804 with insufficient space for an object of type 'int'
0x7ffd0c0c9804: note: pointer points here
08 00 00 00 04 00 00 00

第20、25、30行是

20      while(a[j] < b[k] && j<m ){

25 while(a[j] > b[k] && k<n){

30 while(a[j] == b[k]){

关于c - 为什么我的 C 代码每次都不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com