gpt4 book ai didi

无法弄清楚为什么我在初始化数组时遇到段错误

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

我有以下代码,它适用于 N=10 和 C=25,但如果我使用 N=50 和 C=25500,就会出现段错误

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

// create table
int *table;
table = (int *) malloc(sizeof(int) * C+1 * N+1);
if(table == NULL){
printf("[ERROR] : Fail to allocate memory.\n");
}

// initialize table
for(i =0; i < N-1; i++){
for(j = 0; j < C-1; j++){
//table[i*(C+1)+j]=0;
*(table + (i*(C+1)+j))=1;
}
}
printf("table made\n");

最佳答案

我认为您分配的内存量不正确。您正在分配 C*sizeof(int) + N + 1 并且您想要分配 (C+1)*(N+1)*sizeof(int)< br/>你只是缺少一些 parent -- http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

关于无法弄清楚为什么我在初始化数组时遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21398321/

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