Skip to content

Instantly share code, notes, and snippets.

@DieracDelta
Created February 26, 2025 18:52
Show Gist options
  • Select an option

  • Save DieracDelta/fd9105fc716a10ec8e6d5a8ac3c59248 to your computer and use it in GitHub Desktop.

Select an option

Save DieracDelta/fd9105fc716a10ec8e6d5a8ac3c59248 to your computer and use it in GitHub Desktop.
2d array examples
#include <stdio.h>
#include <stdlib.h>
// EX_0:
// - array declaration
// - array initialization on stack
// - array reads and writes
void ex_0() {
int balance[2][3] = {
{1000, 1000, 1000},
{1000, 1000, 1000}
};
// increment all balances by 1
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
balance[i][j] += 1;
}
}
// print balances
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("balance %d ", balance[i][j]);
}
}
}
// EX_1:
// same as ex_0 but
// demonstrate arrays may be used with other types besides int
// such as structs
typedef struct {
int accountNumber;
int balance;
} BankInfo;
void ex_1() {
BankInfo accounts[2][3] = {
{{201, 1000}, {202, 1000}, {203, 1000}},
{{204, 1000}, {205, 1000}, {206, 1000}}
};
// increment balances
// note the array write
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
accounts[i][j].balance += 1;
}
}
// print account number and balance
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Account number %d with balance %d\n", accounts[i][j].accountNumber, accounts[i][j].balance);
}
}
}
// EX_2
// array stored on stack but initialization done dynamically
void ex_3() {
int accountNumber = 201;
int all_accounts_balance = 1000;
// reserve space on the stack
BankInfo accounts[2][3];
// initialize all values
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
accounts[i][j].accountNumber = accountNumber;
accounts[i][j].balance = all_accounts_balance;
accountNumber++;
}
}
// print balance
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Account number %d with balance %d\n", accounts[i][j].accountNumber, accounts[i][j].balance);
}
}
}
// EX_3
// array stored on heap with dynamic initialization
// exactly the same as ex_2
int ex_4() {
int accountNumber = 201;
double balanceBase = 1000.00;
BankInfo *accounts = (BankInfo*) malloc(2 * 3 * sizeof(BankInfo));
if(accounts == NULL){
return -1;
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
accounts[i*3 + j].accountNumber = accountNumber;
accounts[i*3 + j].balance = balanceBase;
accountNumber++;
}
}
free(accounts);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment