08-29-2022, 01:25 PM
(This post was last modified: 08-29-2022, 01:27 PM by Kernelpanic.)
Quote:JRace - You got it. In C, string literals are one dimensional arrays of characters and can be treated as such.
The square brackets are an index into that array, allowing access to one character at a time.
You can also create multidimensional arrays. In memory they are also stored as an order, but they can be accessed only by row and column specs.
The following example creates a two-dimensional magic square. By specifying row + column, you can specifically access the individual field elements; number <space> number. A field in C starts at zero.
Incorrect entries are not intercepted!
The editor has some problems with a C source text. Well, the competition!
Code: (Select All)
//Zugriff auf Feldelemente - 29. Aug. 2022
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int magisches_quadrat[4][4] = {
{16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}
};
int feldelement1, feldelement2, *zgr;
int *zgr_mag = &magisches_quadrat[0][0];
printf("\nZugriff auf zweidimensionales Feld\n");
//Quadrat ausgeben
printf("\nMagisches Quadrat ausgeben:\n");
for(int i = 0, j = 1; i < 16; i++, j++)
{
printf("%2d ", zgr_mag[i]);
if(j % 4 == 0)
printf("\n");
}
//Zeile, Spalte beginnt in C bei 0!
printf("\nInhalt von [2][3] = %d", magisches_quadrat[2][3]);
printf("\n\nWelches Feldelement soll angezeigt werden?");
printf("\nGeben Sie das Element an[][] - Zahl <> Zahl: ");
scanf("%d %d", &feldelement1, &feldelement2);
printf("\nInhalt von [%2d][%2d] = %2d", feldelement1, feldelement2,
magisches_quadrat[feldelement1][feldelement2]);
printf("\n\n");
return(0);
}
Example: