【问题标题】:Acces violation writing location c ,2D dynamic array访问冲突写入位置 c ,2D 动态数组
【发布时间】:2016-01-12 16:37:11
【问题描述】:

亲爱的用户我正在尝试将数据写入数组,但由于某种原因我一直收到此错误..请帮助我

int** input_array_dyn1(int n,int m) 
{
int i,**a; //index and array we want to set up.
a=(int**)calloc(n,sizeof(int*)); //get room for array in size n of ints.
assert(a); //checking that we have space.
for (i=0;i<n;i++)  //loop for getting value in each cell...
{
a[i]=(int*)calloc(m,sizeof(int)); //get room for array in size n of ints.
assert(a[i]); //checking that we have space.
}
return a; //returning the new array we made.
}

void randomMat(int** a,int n,int m)
 {
int i,j;
for(i=1;i<=n;i++)           
    for(j=1;j<=m;j++)
        a[i][j]=rand()%2;

printf ("you'r first matrix is:\n");
//print_mat(a,m,n);
}

我总是从访问违规写入位置的a[i][j]=rand()%2; 行中得到一个错误 请帮帮我!

【问题讨论】:

  • 没有数组。只有指针指向指针。阅读How to Ask 并提供minimal reproducible example
  • 1) 有空格是有原因的。正确格式化和缩进 2) 不要将malloc 和朋友的结果投射到 C 中!
  • “我收到一个错误......”请更具体。语法错误?段错误?有人进了你的房间给你一张纸?哦,为了明确一点:仍然没有数组。
  • 检查for (i=0;i&lt;n;i++)for(i=1;i&lt;=n;i++)之间的区别。
  • 为了便于我们人类阅读/理解,请始终缩进代码。建议每个缩进级别使用 4 个空格。 (永远不要使用标签)。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。用空行分隔代码块(for、if、else、while、do...while、switch、case、defautl)。

标签: c arrays computer-science


【解决方案1】:

您自己可以看到input_array_dyn1randomMat 中的循环有所不同

例如比较

for (i=0;i<n;i++)  //loop for getting value in each cell...
{
a[i]=(int*)calloc(m,sizeof(int)); //get room for array in size n of ints.
assert(a[i]); //checking that we have space.
}

for(i=1;i<=n;i++)           
    for(j=1;j<=m;j++)
        a[i][j]=rand()%2;

如果数组包含n 元素,则索引的有效范围为[0, n-1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多