gpt4 book ai didi

c - 在c中初始化指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:31 25 4
gpt4 key购买 nike

在下面的代码中,我初始化了 L、R 和数组 like this :

int *L = (int *) malloc(sizeof(int) * n1);
int *R = (int *) malloc(sizeof(int) * n2);

for (i = 1; i <= n1; i++){
L[i] = A[p + i - 1];
}

for (j = 1; j <= n2; j++){
R[j] = A[q + j];
}


int *array = (int *) malloc(sizeof(int) * n);

...
for (c = 0; c < n; c++){
scanf("%d", &array[c]);
}

但是出现了段错误。你能告诉我这个初始化有什么问题吗?

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

void merge(int *A, int p, int q, int r)
{
int n = r - p + 1; /* number of elements in array A */
int n1 = q - p + 1;
int n2 = r - q;
printf("n2 = %d\n",n2);
int i, j, k;

int *L = (int *) malloc(sizeof(int) * n1);
int *R = (int *) malloc(sizeof(int) * n2);

for (i = 1; i <= n1; i++){
L[i] = A[p + i - 1];
}

for (j = 1; j <= n2; j++){
R[j] = A[q + j];
}

L[n1+1] = INT_MAX;
R[n2+1] = INT_MAX;

i = 1;
j = 1;

printf("p = %d\n",p);
printf("r = %d\n",r);

for (k = p; k <= r; k++){
printf("k=%d\n",k);
if (L[i] <= R[j]){
A[k] = L[i];
i += 1;
}

else{
A[k] = R[j];
j += 1;
}
}

free(L);
free(R);
}

void merge_sort(int *A, int p, int r)
{
int i;
/* for (i=0; i<=r-p;i++){
printf("%d\n",A[i]);
}*/
int q;
if (p < r){
/* printf("merge_sort p = %d\n",p);
printf("merge_sort r = %d\n",r);*/
q = (p + r)/2;
/* printf("q = %f\n",q);*/
merge_sort(A, p, q);
merge_sort(A, q+1, r);
/* printf("done\n");*/
merge(A, p, q, r);
}
}


int main()
{
int x, c;
int n;
int *array = (int *) malloc(sizeof(int) * n);
printf("Enter number of elements\n");
scanf("%d",&n);

printf("Enter %d elements\n",n);

for (c = 0; c < n; c++){
scanf("%d", &array[c]);
}

merge_sort(array, 0, n-1);

for (c = 0; c < n; c++){
printf("%d\n", array[c]);
}

free(array);
return 0;
}

最佳答案

malloc n1 的内存和 n2 intLR , 分别。这使得写入索引 L[0] 有效通过L[n1 - 1]R[0]通过R[n2 - 1] ,包括在内,但您的循环写入 L[n1]R[n2]由于条件 i<=n1j<=n2 .将开始更改为 0对于每个循环并删除 = s 来自每个结束条件。

(检查您的其他代码是否存在相同错误也是一个好主意,即记住 0 是第一个索引,它计入数组的长度。)

关于c - 在c中初始化指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945578/

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