gpt4 book ai didi

c - C 中的基本数组和函数 - 自学

转载 作者:行者123 更新时间:2023-11-30 18:39:13 25 4
gpt4 key购买 nike

我对 C 编程语言和 Stack Exchange 非常陌生。我正在自学,最近完善了 Matlab 的基本技能。我试图在下面的 C 代码示例中搞乱数组,我希望我已经在整个过程中对其进行了充分的解释。然而,当我编译代码时,我立即遇到了段错误。我不确定我的冰山在哪里,我正在寻找解决方案,以便我可以通过好的例子来学习。

/* colAdd takes a 4,4 array 'A' and adds columns 'C1' and 'C2', 
placing the result in column 'C1'. Prints matrix 'A'.
Void function as result is only printed, not returned.
Main tests colAdd with simple 4,4 array */

#include <stdio.h>

// Function colAdd is declared
void colAdd(int A[4][4], int C1, int C2);

int main()
{
// Function colAdd is initialised
int A[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
colAdd(A,1,3);
}

void colAdd(int A[4][4], int C1, int C2)
{
int j = 0; int i; int arr1[4]; int arr2[4]; int arr3[4];

// The following takes column C1 of A and places the result in arr1
for(i = (C1 - 1); i = (C1 + 11); i + 4) {
arr1[j] = A[C1][i];
j = j + 1;
}
j = 0;

// The following takes column C2 of A and places the result in arr2
for(i = (C2 - 1); i = (C2 + 11); i + 4) {
arr2[j] = A[C2][i];
j = j + 1;
}

// The following takes the addition of arr1 and arr2 and places the result in arr3
for(i = 0; i = 3; i++) {
arr3[i] = arr2[i] + arr1[i];
}
j = 0;

// The following replaces column C1 of array A with arr3
for(i = (C1 - 1); i = (C1 + 11); i + 4) {
A[C1][i] = arr3[j];
j = j + 1;
}

//Finally, the resultant array A is printed
const int rows = 4;
const int cols = 4;
int k; int l;
for(k = 0; k < rows; k++) {
for(l = 0; l < cols; l++) {
printf("ans[%d, %d] = %d \n", k, l, A[k][l]);
}
}
}

如有任何建议,我们将不胜感激。谢谢大家。

最佳答案

你有:

// The following takes column C1 of A and places the result in arr1
for(i = (C1 - 1); i = (C1 + 11); i + 4) {
arr1[j] = A[C1][i];
j = j + 1;
}

您的代码没有按照您的评论所说的那样执行。您对 for 语句的理解不太正确。

用途:

for(i = 0;  // This is executed only once.
i < 4; // This is executed for every iteration of the loop.
// The loop is terminated if this statement is false.
++i) // This is executed for every iteration after the
// statements of the loop are executed.
{
arr1[i] = A[i][C1];
}

希望这足以让您修复函数的其余部分。

关于c - C 中的基本数组和函数 - 自学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30624428/

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