iterating multi-dimensional arrays in C without knowing index - c

I'm having a problem processing a multidimensional array. I'm trying to get "123" "456" "x123" and "x456" to appear on screen inside a function using pointers:
void f(char ***array){
while (**array != '\0'){
while (*array != '\0'){
printf("%s\n",*array);array++;
}
}
}
int main(){
char* arr[50][50]={{"123","456"},{"X123","X456"}};
f(arr);
return 0;
}
When compiling, I receive the warning passing argument 1 of 'f' from incompatible pointer type at the line f(arr);. and when running the code, I see:
123
456
Segmentation fault
and the program exits.
When I change my code to this:
void f(char **array){
while (*array != '\0'){
printf("%s\n",*array);array++;
}
}
int main(){
char* arr[50]={"123","456"};
f(arr);
return 0;
}
The numbers iterate fine, but I'd rather group my data into sets at some point for better organization. Why does the first set of code with multidimensional array not execute properly?

First, why three stars? What is it that you are trying to accomplish?
The obvious solution is to create a two-dimensional array of characters, then store the string in the array, one per row. Consider the following example:
char arr[][ 6 ] = { "123", "456", "X123", "X456" };
Note that we are allowed to omit the number of rows in the arr array, but C requires that we specify the number of columns. Unfortunately, not all the strings are long enough to fill an entire row of the array, so C padded them with null characters. ( Note that there is a bit of wasted space in the array )
0 1 2 3 4 5
+-----+-----+-----+-----+-----+-----+
0 | 1 | 2 | 3 | '\0'| '\0'| '\0'|
+-----+-----+-----+-----+-----+-----+
1 | 4 | 5 | 6 | '\0'| '\0'| '\0'|
+-----+-----+-----+-----+-----+-----+
2 | X | 1 | 2 | 3 | '\0'| '\0'|
+-----+-----+-----+-----+-----+-----+
3 | X | 4 | 5 | 6 | '\0'| '\0'|
+-----+-----+-----+-----+-----+-----+
If having three stars in your code is what you want, then you will have to add one additional element which is always NULL. ( By the way, why don't you want to use the length of the array? )
Another way is to use a ragged array. C doesn't provide a "ragged array type", but it does give us the tools to simulate one. ( just create an array whose elements are pointers to strings ) Consider the following example:
#define N 4
int main( int argc, const char * argv[] ) {
char *str[] = { "123", "456", "X123", "X456" };
for ( char **p = &str[ 0 ]; p < str + N; ++p ) {
puts( *p );
}
return EXIT_SUCCESS;
}
To access one of the strings, all we need is subscript the arr array.
Hope this helps..

It is hard to tell what you are attempting to do, but if I understand correctly, you appear to have an additional array dimension that isn't required. You are testing an uninitialized value as soon as you reach the 5th string (leading to your segfault). To correct it, you could do something like:
#include <stdio.h>
void f(char **array){
while (*array != '\0'){
// while (*array != '\0'){
printf("%s\n",*array);array++;
//}
}
}
int main(){
char *arr[50]={"123","456","X123","X456",NULL};
f(arr);
return 0;
}
Output
$ ./bin/func_f
123
456
X123
X456
Note: an explicit NULL is used as a sentinel to stop iterating when the data is exhausted. There are a number of ways to handle this, this being only one.

You generally shouldn't use pointers and arrays interchangeably. The common knowledge is that they're the same, but they aren't. This is particularly true for multi-dimensional arrays.
Multidimensional arrays have to be laid out linearly in memory, since addresses are linear. There are a couple ways to do this, but C uses row-major ordering. What this means is that the last index increases fastest as addresses increase.
For example, a two dimensional array
int x[rows][cols];
the two statements would be equivalent
x[row][col] = y;
*(x + (row * cols) + col) = y;
What this means is that in order to access the elements of your multi-dimensional array in a function, the function needs to know at least the sizes of the higher dimensions to validly access.
void f(int rows, int cols, char* array[rows][cols]){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%s\n", array[i][j]);
}
}
}
int main(){
char* arr[50][50]={{"123","456"},{"X123","X456"}};
f(50, 50, arr);
return 0;
}
However, if it is necessary to iterate without knowing the dimensions, you can take advantage of the memory layout to effectively iterate over rows and columns (and higher dimensions). Although, this adds the necessity for an entry in the array that signals an end (e.g. NULL). Aside from making the code more complex, it adds memory overhead since the last row containing the NULL generally must be allocated.
#include <stdio.h>
void f(char** array){
while (*array)
printf("%s\n", *(array++));
}
int main(){
char* arr[][2] = { {"123","456"}, {"X123","X456"}, {NULL, NULL} };
f((char**) arr);
return 0;
}

Related

Dynamically allocating 2d array in c error

My problem is prettty simple, I wanna allocate memory for a 2d array in c, fill it with -1, then free it and exit the program. My code keeps crashing and I dont know what I am doing wrong...
This is what I got:
int main(){
int i,j;
char str1[]="xxxabxcxxxaabbcc";
char str2[]="abc";
int len1=strlen(str1);
int len2=strlen(str2);
printf("%d %d",len1,len2);
//allocate 2d_array
int **H_table = (int**)malloc((len1+1)*sizeof(int));
for (i=0; i<len1+1; i++){
H_table[i] = (int*)malloc((len2+1)*sizeof(int));
}
//fill and print 2d array
for(i=0;i<len1+1;i++){
for(j=0;j<len2+1;j++){
printf("i:%d j:%d",i,j);
H_table[i][j]=-1;
printf(" value:%d\n",H_table[i][j]);
}
}
// free 2d array
for(i=0;i<len1;i++){
free(H_table[i]);
}
free(H_table);
return 0;
}
So what happens is that I wanna allocate an array that has 1 extra line and 1 extra column than the 2 strings if you put them vertically compared to each other.
And this is what I expected( the things in bracets are obviously not part of the table, I put the there for comparison):
(x x x a b x c x x x a a b b c c)
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
a)1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
b)1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
c)1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The problem is that the code crashes when it fills the table, and it always crashes for i=9 and j=3, for those specific strings. The weird part is that if you swap the 2 strings(put "abc" in str1) then the code passes the filling stage, and crashes when it tries to free the array.
Sorry for any grammar mistakes or stackoverflow mistakes, I am kinda new here :P
Any idea is welcome :) thx in advance
As a number of people have pointed out, you're allocating H_table with room for len1 + 1 integers but it is actually supposed to be an array of len1 + 1 pointers (to integers). Since pointers are bigger than integers (on your system, anyway), you end up with undefined behaviour from a buffer overrun.
Here's a hint. Avoid this problem, and a variety of other similar issues, by always using the following model for malloc:
some_variable = malloc(n * sizeof *some_variable);
For example:
int** H_table = malloc((len1 + 1) * sizeof *H_table);
for (int i = 0; i <= len1; ++i)
H_table[i] = malloc((len2 + 1) * sizeof *H_table[i]);
That is, let the compiler figure out the right type for the variable (or lvalue). The compiler is less prone to typos than you are, and not writing the type explicitly will make it a lot easier for you to later decide that H_table should have been long or short or unsigned.
For the same reason, don't explicitly cast the return value of malloc. C automatically casts void* to the destination type, and does not provide an error if you manually cast to the wrong type. So just let the compiler do it; it's less typing, safer, and more future-proof.
Note that if you use an expression with sizeof, the compiler does not evaluate the expression [Note 1]. It just figures out the type and substitutes that for the expression. So don't worry about extra evaluation: there isn't any. That's also why it's ok to use this model with declarations, even though some_variable doesn't yet have a value when the malloc is executed.
Notes:
There is one circumstance in which the compiler might evaluate ex in sizeof ex: if ex is a variable-length array. However, in this case ex is always a pointer, so that case cannot apply.
As #xing mentioned in his comment, H_table is a pointer to pointer to integer. so you need to change the int to int* in the first malloc.
here:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i,j;
char str1[]="xxxabxcxxxaabbcc";
char str2[]="abc";
int len1=strlen(str1);
int len2=strlen(str2);
printf("%d %d",len1,len2);
//allocate 2d_array
int **H_table = (int**)malloc((len1+1)*sizeof(int*));
for (i=0; i<len1+1; i++){
H_table[i] = (int*)malloc((len2+1)*sizeof(int));
}
//fill and print 2d array
for(i=0;i<len1+1;i++){
for(j=0;j<len2+1;j++){
printf("i:%d j:%d",i,j);
H_table[i][j]=-1;
printf(" value:%d\n",H_table[i][j]);
}
}
// free 2d array
for(i=0;i<len1;i++){
free(H_table[i]);
}
free(H_table);
return 0;
}

Using 2d arrays to store strings in C

I want to make a program that handles strings in 2d arrays in the following manner:
Each row represents one name only, while columns holds separate characters of each name.
Like so:
0 1 2 3 4 5
0 K e v i n \0
1 J o h n \0
2 L u c y \0
Now, the way I understand arrays is that they work as pointers for the first element. So when I read the string using the readstring(name) function even though I used a 1D array, it should work as a pointer to the 2D array and store each string as I showed above, right?
The following code is supposed to ask for three names then print them all, but it only prints the last name and some gibberish, what did I do wrong?
#include <stdio.h>
#include <stdlib.h>
void readstring(char name[]);
void get_data(char name[][15]);
void show_data(char name[][15]);
int main()
{
char name[3][15];
get_data(name);
show_data(name);
return 0;
}
void get_data(char name[][15]){
int i=0;
for(i=0;i<3;i++){
printf("\nEnter name: ");
readstring(name);
}
}
void show_data(char name[][15]){
int i;
for(i=0;i<3;i++){
printf("%s",name[i]);
}
}
void readstring(char str[]){
int i=0;
while((str[i++]=getchar())!='\n' && i<15);
str[i]='\0';
}
The output shows like this:
http://i58.tinypic.com/e7i048.jpg
The problem is here:
readstring(name);
Change it to:
readstring(name[i]);
The problem is that name is a 2 - d array, or , an array of strings. Therefore, to access one string in the array of strings, you need to use an index for that particular string.
In fact, the calling function readstring() expects a string as an argument.

Sorting an array by second string

I have a textfile with name followed by a number that is the priority of the name, now I'm trying to sort the textfile by priority and write a new file.
old
name1 1
name2 2
name3 3
name4 1
name5 1
name6 2
name7 1
name8 3
new
name 1 1
name4 1
name5 1
name2 2
name6 2
name3 3
name8 3
I have achieved to get the old textfile in an array, but I'm stuck with sorting that array by priority. I shouldn't loop through the file again, just wanna sort the array then write that new sorted array to a new text file. How should I proceed??
The code
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int p;
char *name;
}names;
int main(void){
FILE *old= fopen("old.txt", "r");
FILE *new = fopen("new.txt", "w");
char n[10];
int i =0;
names *name= malloc(sizeof(names));
for(i; i<count; i++){
int p;
char *n= malloc(sizeof(char) * 4);
fscanf(old, "%s %i", n, &p);
names[i].name= n;
names[i].p= p;
}
int j=0;
for(i=0; i < count;i++){
}
return 0;
}
Assuming that you cannot use qsort() because one of your constraints is to write your own sorting algorithm, here goes.
What do you need to sort? An array ofjob.
What is the key by which you need to sort? job.prio.
So how to sort? Any common selection, insertion, or (eek) bubble sort will do. (Though if you go down the bubble sort route, at least make it sexy and do a cocktail shaker sort.) Just compare two job.prios, both are ints so that's not hard, and swap the places of their respective job structures in the array as needed.
Here is a selection sort algorithm that will work. You can find plenty of others on Google.
void selectionSort (job* jobs, int size) {
int smallest;
job temp;
for (int i = 0; i < size - 1; i++) {
smallest = i;
for (int walk = i + 1; walk <= size - 1; walk++) {
if (jobs[walk].prio < jobs[smallest].prio)
smallest = walk;
} // end inner loop
temp = jobs[i];
jobs[i] = jobs[smallest];
jobs[smallest] = temp;
} // end outer loop
return;
}
Fairly simple; it's just like any old selection sort. But selection sort is boring. Try to do an insertion sort, now that the selection sort gives you the general idea of how to swap the elements in the array.
Note that there are other problems with your code, as folks have pointed out: you are allocating space for only one job in your array, but you need eight; you have undefined variables like eerste; you have name declared twice, once as a char* and once as an array of char. So there's plenty of cleanup, but hopefully you have enough idea now to be able to finish your assignment.
You should sort using the qsort() standard library function.
It will require you to implement a function that compares two job structures, in order to provide the sorting.
Here's one attempt:
static int compare_jobs(const void *a, const void *b)
{
const job *ja = a, *jb = b;
return ja->prio < jb->prio ? -1 : ja->prio > jb->prio;
}
You will need to call this properly (read the documentation!), then loop over your array and write the contents to a new file.

Use of array of arrays of string in C for parsing text file

I would like to read from N text files (having similar structure: a few lines, each line having the same small number of words) and store in a string matrix the words read, in such a way that in each (row, col) position I have one word.
A simple (two lines, three words per line) specimen for the files is the following:
line1word1 line1word2 line1word3
line2word1 line2word2 line2word3
Delimiter for the words is space.
I have attempted this code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 1000
#define MAX_TOKS 100
#define DELIMITERS " "
// line parsing utility
int parseString(char* line, char*** argv) {
char* buffer;
int argc;
buffer = (char*) malloc(strlen(line) * sizeof(char));
strcpy(buffer,line);
(*argv) = (char**) malloc(MAX_TOKS * sizeof(char**));
argc = 0;
(*argv)[argc++] = strtok(buffer, DELIMITERS);
while ((((*argv)[argc] = strtok(NULL, DELIMITERS)) != NULL) &&
(argc < MAX_TOKS)) ++argc;
return argc;
}
int main() {
char S[MAX_STRING_LENGTH];
char **A;
int n,i,j,l;
FILE *f;
char file[50];
char ***matrix;
matrix = malloc(MAX_TOKS * sizeof(char**));
//memory allocation for matrix
for (i = 0; i < MAX_TOKS; i++)
{
matrix[i] = malloc(MAX_TOKS * sizeof(char *));
for (j = 0; j < MAX_TOKS; j++)
{
matrix[i][j] = malloc(MAX_TOKS * sizeof(char));
}
}
int NFILE = 10; // number of files to be read
for(i=0;i<NFILE;i++)
{
sprintf(file,"file%d.txt",i);
f = fopen(file,"r");
l=0; // line-in-file index
while(fgets(S,sizeof(S),f)!=NULL) {
n = parseString(S,&A);
for(j=0;j<n;j++) {
matrix[i][l]=A[j];
printf("%s\t%s\n",matrix[i][l],A[j]);
}
l++;
}
fclose(f);
}
free(matrix);
free(A);
return(0);
}
The problem I can't solve is that there when checking for correspondance between the arrays (in order to be sure I am storing the single words correctly) using
printf("%s\t%s\n",matrix[i][l],A[j]);
I find that the last word (and only the last one) of each line, regardless of the file number, is not stored in matrix. That is to say, line1word1 and line1words of file0 are correctly stored in matrix[0][0][0] and matrix[0][0][1], but in the field matrix[0][0][2] there isn't line1word3, even if A[2] has it!
What am I doing wront? Any suggestion?
Many thanks in advance,
cheers
char ***matrix doesn't declare a three dimensional array. Your matrix would need to be something like char *matrix[a][b] to hold a two dimensional array of string pointers. In order to calculate addresses within an array, the compiler needs to know the all of dimensions but one. If you think about it, you will probably see why...
If you have two arrays:
1 2 3 1 2 3 4 5 6 7
4 5 6 8 9 10 11 12 13 14
7 8 9 15 16 17 18 19 20 21
You can see that item[1][1] is NOT the same item. Regardless of the dimensions in your array, the elements are typically arranged sequentially in memory, with each row following the previous (or possible column, depending on language, I suppose.) If you have an array of pointers, the actual content may be elsewhere, but the points would be arranged like this. So, in my examples above, you must provide the compiler with the number of columns so that it can find members (the number of rows can be variable.) In a three dimensional array, you must provide the first TWO dimensions so that the compiler may calculate item offsets.
I hope that helps.
EDIT: You can have truly dynamic array dimensions by creating your own function to process all array item accesses. The function would need to know the dynamic dimensions and the item index(s) so that it could calculate the appropriate address.
This looks wrong: buffer = (char*) malloc(strlen(line) * sizeof(char));
Firstly, there is no need to cast malloc in C. If your code doesn't compile without the cast, there are two possible reasons:
There is no prototype for malloc. Obviously this can cause problems, because no prototype means the function returns a default type: int, or an error occurs. This can cause your program to misbehave. To avoid this, #include <stdlib.h>.
You're using a C++ compiler. Stop. Either program in C++ (stop using malloc) or use a C compiler. If you want to use this project in a C++ project, compile your C code with a C compiler and link to it in your C++ compiler.
Secondly, sizeof(char) is always 1. There is no need to multiply by it.
Thirdly, a string is a sequence of characters ending at the first '\0'. This means a string always occupies at least 1 character, even if it is an empty string. What does strlen("") return? What is sizeof("")? You need to add 1 to make room for the '\0': buffer = malloc(strlen(line) + 1);.
This looks slightly wrong: (*argv) = (char**) malloc(MAX_TOKS * sizeof(char**));
malloc returns a pointer to an object. *argv is a char **, which means it points to a char *. However, in this case malloc returns a pointer to char ** objects. The representation isn't required to be identical. To avoid portability issues assosciated with this, follow this pattern variable = malloc(n * sizeof *variable); ... in this case, *argv = malloc(MAX_TOKS * **argv);
It gets more gritty as it goes. Forget everything you think you know about your code; Pretend you're going to come back to this in 24 months. What are you going to think of this?
argc = 0;
(*argv)[argc++] = strtok(buffer, DELIMITERS);
while ((((*argv)[argc] = strtok(NULL, DELIMITERS)) != NULL) &&
(argc < MAX_TOKS)) ++argc;
There's actually an off-by-one here, too. Assuming argc == MAX_TOKS, your loop would attempt to assign to (*argv)[MAX_TOKS]. This loop is where I believe your problem lies, and the solution is to express your intent more clearly rather than attempting to cram as much code into one line as possible. How would you rewrite this? Here's what I'd do, in this situation:
char *arg;
size_t argc = 0;
do {
arg = strtok(buffer, DELIMITERS);
buffer = NULL;
(*argv)[argc] = arg;
argc++;
} while (argc < MAX_TOKS && arg != NULL);
The problem is that your parsing loop doesn't increment when strtok returns NULL. Hence, your function returns the position of the last item. Supposing you had two tokens, your parsing function would return 1. Your display loop displays items up to, but not including this position: for(j=0;j<n;j++). You could use the suggested improvement, or change your loop: for (j = 0; j <= n; j++). Either way, you'll need to fix those off-by-ones.
Out of curiosity, which book are you reading?

Matrix with variables in C

I'm going to write in pseudo code to make my question more clear. Please keep in mind this code will be done in C.
Imagine I have an array of any amount of numbers. The first number tells me how big of an array we're dealing with. For example, if my first number is 3, it means I have two 3x3 matrices. So I create two multidimensional arrays with:
matrix1[3][3]
matrix2[3][3]
What I'm having a hard time with is the arithmetic/coding to assign all the numbers to the matrices, I'm having a very hard time visualizing how it would be done.
Imagine a test array contains [2,1,2,3,4,5,6,7,8]
My program should now have two matrixes with:
1 2 5 6
3 4 7 8
Do I need several nested loops? Any help would be appreciated.
At the moment the only idea i get is using two for loops. Or you can make a function and call it every time you need (but don't forget to use k as second argument).
int i, j, k;
/* We start in the 2nd element of the array that's why k = 1. */
k = 1;
/* Now we fill the array1 copying 1 by 1 the elements of the "test array" until
we fill it. Then we do the same with the array2. */
for( i = 0; i < test[ 0 ]; i++ ){
for( j = 0; j < test[ 0 ]; j++ ){
array1[ i ][ j ] = test[ k ]
k++;
}
}
for( i = 0; i < test[ 0 ]; i++ ){
for( j = 0; j < test[ 0 ]; j++ ){
array2[ i ][ j ] = test[ k ]
k++;
}
}
Your data is presented in row-major order. After reading your integer array and validating the content (i.e. the dim=4 means 32 values follow, dim=2 means 8 values follow, etc.) I'm not sure why you want to allocate or loop anything.
I.e. You can use your physical test[] data as the matrices:
int dim = test[0];
int (*mat1)[dim] = (int (*)[dim])(test+1);
int (*mat2)[dim] = (int (*)[dim])(test+1 + dim*dim);
C99 supports variable array declarations at the implementation level (i.e. the compiler can support the feature as it is defined by the standard, but does not have to; see 6.7.6.2 of the C99 standard for more info). If your toolchain does NOT support it, then a predefined macro, __STDC_NO_VLA__ must be defined and can be tested at compile time (see section 6.10.8.3-1 of the C99 standard). That being said, every C99-compliant compiler I've ever used in the last decade-plus does support it, so if your's does not, tell us below in a comment.
If it does, then pay note to the use of 'dim' in the declarations of mat1 and mat2 above). It is one of the few features of C I like that C++ does not have. So dance with the one you brought.
Finally, assuming your compiler is C99 compliant and supports VLAs (__STDC_NO_VLA__ is NOT defined), as an extra super-special bonus it is all-but-guaranteed to be the fastest algorithm to get your two matrices, because there is no algorithm. You read one array element, then assign two pointers. O(3) is hard to beat.
Example
#include <stdlib.h>
#include <stdio.h>
// main loader.
int main(int argc, char *argv[])
{
int test[] = {2,1,2,3,4,5,6,7,8};
int dim = test[0];
int (*mat1)[dim] = (int (*)[dim])(test+1);
int (*mat2)[dim] = (int (*)[dim])(test+1 + dim*dim);
// proof stuff is where it should be.
int i=0,j=0;
for (i=0;i<dim;i++)
{
for (j=0;j<dim;printf("%d ", mat1[i][j++]));
printf (" ");
for (j=0;j<dim;printf("%d ", mat2[i][j++]));
printf("\n");
}
return EXIT_SUCCESS;
}
Output
1 2 5 6
3 4 7 8
A similar test with a 3x3 data set:
int test[] = {3,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1};
Output
1 2 3 9 8 7
4 5 6 6 5 4
7 8 9 3 2 1
And finally, a 4x4 data set:
int test[] = {4,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,8,7,6,5,4,3,2,1,8,7,6,5,4,3,2,1};
Output
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
1 2 3 4 8 7 6 5
5 6 7 8 4 3 2 1
The problem with multidimensional arrays in C is that you need to know in advance (at compile time) n-1 of the dimension sizes, they are also a drag when used as function parameters.
There are a couple of alternate approaches:
Creating an array of arrays. i.e. allocating an array of array pointers and then allocating arrays to those pointers.
type **array = malloc(sizeof(type * ) * < firstnumread > );
array[0] = malloc(sizeof(type) * < firstnumread > );
...
Allocating a single dimension array with the size of all the multiplied dimensions. i.e.
type *array = malloc(sizeof(type) * < firstnumread > * < firstnumread >);
In your case, the second is probably more appropiate. Something like:
matrix1 = malloc(sizeof(type)*<firstnumread>*<firstnumread>);
matrix2 = malloc(sizeof(type)*<firstnumread>*<firstnumread>);
Then you can assign values like this:
matrix1[column*<firstnumread> + row] = <value>;
Yes, with 2 for loops.
2D arrays are stored in continuous series of lines from the matrix. So you doesn't even need to allocate new memory you can use your original array. Anyway you can create 2 new standalone array too.
You can crate a function like this, to get the correct number of the matrix.
int getNumber(int array[], int arraynumber, int index_x, int index_y)
{
return array[(((array[0]*index_x)+index_y)+1)+((array[0]*array[0])*arraynumber)];
}
The arraynumber variable is 0 for the first and 1 for the second matrix. This funciton works only if all parameters are correct, so ther is no error detection.
With this function you can easily loop through and create 2 new arrays:
int i,k;
for (i=0; i<array[0]; i++)
{
for (k=0; k<array[0]; k++)
{
newarray1[i][k] = getNumber(array, 0, i,k);
newarray2[i][k] = getNumber(array, 1, i,k);
}
}
Here is something that works in a single loop; no nests and no repeats. I don't know if it'll outperform other answers, but I just felt like giving you a different answer ^_^
I have not tested this code, but it looks like the logic of the algorithm works - that's the point, right? Let me know if it has any errors....
int c=0, x=0, y=0, size=test[0], length=sizeof(test);
for(i=1; i<length; i++) {
if((c-size)<0) {
matrix1[x][y] = test[i];
} else {
matrix2[x][y] = test[i];
}
++y;
if(y%size == 0) {
++c;
y = 0;
x = (c-size)<0 ? ++x : 0;
}
}

Resources