I need to have a function which takes a 2D array and generates random bits, so the result is an array of random binary strings.
I have the following code,
#define pop_size 50
#define chrom_length 50
main() {
int population[pop_size][chrom_length];
init_pop(&population);
}
int init_pop(int *population[][]) {
for(i = 0; i < pop_size; i++) {
for(j = 0; j < chrom_length; j++) {
*population[i][j] = rand() % 2;
}
}
return 0;
}
On compilation, I am getting the following error message:
array type has incomplete element type
Any suggestions?
Time for the usual spiel...
When an array expression appears in most contexts, its type is implicitly converted from "N-element array of T" to "pointer to T", and its value is set to point to the first element of the array. The exceptions to this rule are when the array expression is an operand of either sizeof or the unary & operators, or if it is a string literal being used as an initializer in a declaration.
What does all that mean in the context of your code?
The type of the expression population is "pop_size-element array of chrome_length-element arrays of int". Going by the rule above, in most contexts the expression population will implicitly be converted to type "pointer to chrome_length-element arrays of int", or int (*)[chrome_length].
The type of the expression &population, however, is "pointer to pop_size-element array of chrome_length-element arrays of int", or int (*)[pop_length][chrome_size], since population is an operand of the unary & operator.
Note that the two expressions have the same value (the address of the first element of the array), but different types.
Based on the code you've written, where you call the function as
init_pop(&population);
the corresponding function definition should be
int init_pop(int (*population)[pop_size][chrome_length]) // note that both dimensions
// must be specified
and you would access each element as
(*population)[i][j] = initial_value;
Note that this means init_pop can only deal with pop_size x chrome_length arrays; you can't use it on arrays of different sizes.
If you call the function as
init_pop(population); // note no & operator
then the corresponding function definition would have to be
int init_pop(int (*population)[chrome_length]) // or population[][chrome_length],
// which is equivalent
and you would access each element as
population[i][j] = initial_value;
Note that you don't have to dereference population explicitly in this case. Now you can deal with arrays that have different population sizes, but you're still stuck with fixed chromosome lengths.
A third approach is to explicitly pass a pointer to the first element of the array as a simple pointer to int and treat it as a 1D array, manually computing the offsets based on the array dimensions (passed as separate parameters):
init_pop(&population[0][0], pop_size, chrome_length);
...
int init_pop(int *population, size_t pop_size, size_t chrome_length)
{
size_t i, j;
...
population[i*chrome_length+j] = initial_value;
...
}
Now init_pop can be used on 2D arrays of int of different sizes:
int pop1[10][10];
int pop2[15][20];
int pop3[100][10];
...
init_pop(&pop1[0][0], 10, 10);
init_pop(&pop2[0][0], 15, 20);
init_pop(&pop3[0][0], 100, 10);
...
EDIT: Note that the above trick only works with contiguously allocated 2D arrays; it won't work with dynamically allocated arrays where the major dimension and the minor dimensions are allocated separately.
Here's a handy table, assuming a definition of int a[N][M]:
Expression Type Implicitly converted to
---------- ---- -----------------------
a int [N][M] int (*)[M]
a[i] int [M] int *
a[i][j] int
&a int (*)[N][M]
You need to tell the compiler all dimensions except the first, when passing arrays as arguments:
int init_pop(int population[][pop_size])
{
...
}
Yes, this means it's hard to make it completely dynamic and introduces a place where you have to repeat yourself.
UPDATE: I was confused, and had the requirement inverted. Fixed now.
For multidimensional arrays in C/C++ you have to specify all dimensions except the first.I am modifying your program to make it work correctly:
#include <stdio.h>
#include <stdlib.h>
#define pop_size 3
#define chrom_length 3
void init_pop(int population[][chrom_length]) {
int i,j;
for(i = 0; i < pop_size; i++) {
for(j = 0; j < chrom_length; j++) {
population[i][j] = rand() % 2;
}
}
}
/* For Checking */
void display (int population[][chrom_length]){
int i,j;
for(i = 0; i < pop_size; i++) {
for(j = 0; j < chrom_length; j++) {
printf("%d ",population[i][j]);
}
printf("\n");
}
}
int main(void) {
int population[pop_size][chrom_length];
init_pop(population);
display(population); /* For Checking */
return 0;
}
If you not going to use global constants here is the correct way of doing it.
This is the problem:
int *population[][]
A multidimensional array is simply a block of continuous memory, and when you say foo[3][2], the compiler finds the right index by 3*last_dimension_size + 2, which means that it has to know the size of all the dimensions except the last one.
So that declaration is an error.
BTW-- There are several very complete discussion of issues related to multidimensional arrays in c already on SO. Try searching under both or either [c] and [c++]
Related
I have been researching and testing my knowledge in C (I am a new computer engineering student), and ran into a problem I cannot figure out.
When trying to pass a 2D array to a function, I learned that you cannot do so with dynamically allocated arrays, since the compiler needs to know array[][columns]. However, I learned that a 2D array is stored a 1D array, where the elements of each new row just follows the elements of the previous row. When I pass an array name to a function as a pointer to an array, this seems to be the case, and my code works fine. However, in the function where the 2D array is declared, it behaves as an array of pointers instead.
#include <stdio.h>
void printArray(int *A, int* dimA) {
for(int i = 0; i < dimA[0]; ++i) {
for(int j = 0; j < dimA[1]; ++j) {
printf("%3d", A[i*dimA[1] + j]);//This would work if the elements of A[] are the rows of a 2D array mapped into a 1D array
}
printf("\n\n");
}
return;
}
int main(){
int A[2][2] = {{1,2},{3,4}};
int dimA[2] = {2,2};//dimensions of the array
int i, j;
for(i = 0; i < dimA[0]; ++i) {
for(j = 0; j < dimA[1]; ++j) {
printf("%3d", *(A[i] + j)); //This would work if the elements of A[] are pointers
}
printf("\n\n");
}
for(i = 0; i < dimA[0]; ++i) { //Same code as printArray function
for(j = 0; j < dimA[1]; ++j) {
printf("%3d", A[i*dimA[1] + j]);//This would work if the elements of A[] are the rows of a 2D array mapped into a 1D array
}
printf("\n\n");
}
printArray(A, dimA);
return 0;
}
The following code outputs the array correctly in main() when the array is treated as an array of pointers, but not when treated as a 1D array of integers. However, when I pass the same array to the printArray function as a pointer, I can treat it as a 1D array of integers and it works. Any help would be appreciated (I already understand that I can instead use an array of pointers, but I really want to understand what the problem was). Thanks!
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array
object has register storage class, the behavior is undefined.
Thus in the first for loop
for(i = 0; i < dimA[0]; ++i) {
for(j = 0; j < dimA[1]; ++j) {
printf("%3d", *(A[i] + j)); //This would work if the elements of A[] are pointers
}
printf("\n\n");
}
the expression A[i] has the type int[2]. Being converted to pointer it has the type int *. So for each i the expression A[i] points to the first element of each "row" of the array A.
The expression A[i] + j points to the j-th element of each row. So dereferencing the pointer you get j-th element of the i-th row of the array.
In the second loop
for(i = 0; i < dimA[0]; ++i) { //Same code as printArray function
for(j = 0; j < dimA[1]; ++j) {
printf("%3d", A[i*dimA[1] + j]);//This would work if the elements of A[] are the rows of a 2D array mapped into a 1D array
}
printf("\n\n");
}
the expression A[i*dimA[1] + j] has the type int * and points to i *dimA[1] + j "row" of the array that is it points beyond the array. So the loop does not make sense.
The function declared like
void printArray(int *A, int* dimA);
is called like
printArray(A, dimA);
The second argument that has the type int[2] is indeed converted to pointer of the type int * that points to the first element of the array.
As for the first argument then it is also converted to pointer to its first element. And what is the element of the array? The element of this two-dimensional array is a one-dimensional array of the type int[2]. So pointer to an object of this type will have type int ( * )[2]
Pointers int * and int ( * )[2] are not compatible and by this reason the compiler shall issue a diagnostic message.
the correct declaration of the function should look like
void printArray(int ( *A )[2], int *dimA);
When trying to pass a 2D array to a function, I learned that you cannot do so with dynamically allocated arrays, since the compiler needs to know array[][columns].
This is true, in the sense that you cannot pass any array to a function. You cannot even express such a concept in C, though you can write code that looks like that to the casual eye. In almost every context where an expression evaluating to an array appears -- including function call expressions -- the array value is replaced by a pointer to the first array element.
It is partially true in the sense that a 2D array is an array of arrays, and the dimension of the (array) element type is is part of the overall array's type, part of the type of every element, and part of the type of a pointer to the first element. As such, that dimension must be part of the type of any function parameter to which you want to pass (a pointer to the first element of) the array.
It is most accurately characterized as false, however, even for 2D arrays both of whose dimensions are determined at run time. Since 1999, C has supported variable-length arrays (though in C11 it was made optional), and these play very nicely indeed with dynamically-allocated multi-dimensional arrays and with pointers to arrays of varying dimension:
// Dynamically allocating a 2D array of runtime-determined dimensions:
unsigned rows = calculate_number_of_rows();
unsigned columns = calculate_number_of_columns();
int (*matrix)[columns] = malloc(rows * sizeof(*matrix));
They work well for functions accepting such pointers, too:
void do_something(unsigned rows, unsigned columns, int matrix[rows][columns]);
... or, equivalently ...
void do_something(unsigned rows, unsigned columns, int matrix[][columns]);
... or ...
void do_something(unsigned rows, unsigned columns, int (*matrix)[columns]);
Those three forms are completely equivalent.
However, I learned that a 2D array is stored a 1D array, where the elements of each new row just follows the elements of the previous row.
A 2D array is an array of 1D arrays. The elements of any array are stored contiguously in memory without padding, so the layout of a 2D array of dimensions (r, c) cannot be distinguished from the layout of a 1D array of dimension r * c, but I recommend against thinking of it in the terms
you used.
When I pass an array name to a function as a pointer to an array, this seems to be the case, and my code works fine.
Do not do that. In practice, it is very likely to work exactly as you say, but you should heed the warnings emitted by your compiler -- and it definitely should be emitting warnings about that.
However, in the function where the 2D array is declared, it behaves as an array of pointers instead.
You've not presented an example of a function that would fit your description. Certainly it is possible to pass an array of pointers, but it is quite possible to pass a pointer to an array instead. See above for examples.
Compiling the code gives a warning that is a bit of a clue to what is going on:
main.c:27:27: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("%3d", A[i*dimA[1] + j]);//This would work if the elements of A[] are the rows of a 2D array mapped into a 1D array
~~~ ^~~~~~~~~~~~~~~~
main.c:32:16: warning: incompatible pointer types passing 'int [2][2]' to parameter of type 'int *' [-Wincompatible-pointer-types]
printArray(A, dimA);
^
main.c:3:22: note: passing argument to parameter 'A' here
void printArray(int *A, int* dimA) {
When you declare your array:
int A[2][2] = {{1,2},{3,4}};
this is stored as one contiguous chunk of memory, as you stated. In memory, this is equivalent to:
int A[4] = {1,2,3,4};
However, whenever you go to lookup/dereference the values, depending on the type, the compiler is implicitly doing some bookkeeping for you. For the second case:
int A[4] = {1,2,3,4};
A[0] = *(&A + 0) = 1
A[1] = *(&A + 1) = 2
...
fairly straightforward, the index is simply an offset off the base address. However, for the first case:
y x
int A[2][2] = {{1,2},{3,4}};
y x
A[0][0] = *(&A + 2 * 0 + 0) = *(&A + 0) = 1
A[1][0] = *(&A + 2 * 1 + 0) = *(&A + 2) = 3
...
things start to look a bit confusing.
The first thing to note is that since the type is declared as an int[2][2], you must dereference it twice. That is what the first warning is complaining about. Because it was only dereferenced once, your int ** became an int *, which is not the same as an int.
The second thing to notice is because the type is declared as a multi-dimensional array, the compiler will do some bookkeeping for you. Since the array was being dereferenced on the first dimension, the size of the second dimension to stride to the correct location was already taken into account, so instead of col * j + i, you actually got col * (col * j + i) + i, which is not what you want!
To get the desired effect, you can either:
Cast A into an int *. This is what happened when you called your printArray function, and also why it works.
Access the array from the lowest dimension. Instead of saying A[i*dimA[1] + j], do A[0][i*dimA[1] + j]. This will correctly dereference to an int and also effectively bypass the bookkeeping.
So I am working on an assignment and I am having trouble figuring out how to use this 2d array which was passed by reference.
What I am given is this
int main(){
//cap and flow initialized
maximum_flow(1000, &(cap[0][0]), &(flow[0][0]));
}
So I wanted to copy the contents of cap over to another 2d array I dynamically allocated, but after hitting an error I decided to print out the values I have in cap2 and capacity, I'm not getting back all the values that I should.
void maximum_flow(int n, int *capacity, int *flow){
int **cap2;
cap2 = (int**) malloc(sizeof(int *)*n);
for (i = 0; i < n; i++)
{
cap2[i] = (int*) malloc(sizeof(int)*n);
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cap2[i][j] = (*(capacity + i*n + j));
(*(flow + i*n + j)) = 0;
}
}
}
This isn't going to be a terribly useful answer, since your code doesn't actually show the problem described; based on what's presented, I see no obvious reason why cap and cap2 shouldn't have the same contents by the end of the maximum_flow function. But I'd like to offer some background and a suggestion.
I'm going to assume cap and flow are declared as n by n arrays of int in main, where n is known at compile time.
The reason your instructor is using this interface is that passing multidimensional arrays as function arguments is problematic in C. Remember that unless it's the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaraiton, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.
So, assuming a declaration like
int cap[10][10];
int flow[10][10];
the expressions cap and flow will each "decay" to type int (*)[10] (pointer to 10-element array of int). So if you wrote your function call as
maximum_flow( 1000, cap, flow );
then the function definition would have to be written as
void maximum_flow( int n, int (*cap)[10], int (*flow)[10] ) { ... }
or
void maximum_flow( int n, int cap[][10], int flow[][10] ) { ... }
In the context of a function parameter declaration, T a[][N] and T (*a)[N] mean the same thing.
The size of the outer dimension has to be specified in the array pointer declaration, and the problem is that a pointer to a 10-element array is a different, incompatible type from a pointer to an any-value-other-than-10-element array; thus, maximum_flow could only ever be used for N x 10-element arrays, limiting its usefulness. One way around this problem is to have the function receive an explicit pointer to the first element, and treat that pointer as a 1D array of size N * M.
Long story short, since you're treating your input parameters as 1D arrays, you are probably better off creating cap2 as a 1D array as well:
int *cap2 = malloc( sizeof *cap2 * n * n );
...
cap2[i * n + j] = capacity[i * n + j]; // use array subscript notation instead
flow[i * n + j] = 0; // of explicit dereferences
From the code you've posted, it's not clear what maximum_flow is supposed to do, nor why you need cap2. Note also that at some point you need to free the memory allocated to cap2, otherwise you have a memory leak.
If you're using a C99 or later compiler, you should be able to use a variable-length array instead of malloc:
int cap2[n * n]; // or int cap2[n][n], but like I said above, if you're
// treating your inputs as 1D arrays, you should also treat
// cap2 as a 1D array.
The advantage of a VLA is that you don't need to know the size at compile time, and it's treated like any other auto variable, meaning the memory for it will be released when the function exits.
The disadvantage of a VLA is that you can't use it as anything but a local variable; you can't have a VLA as a struct or union member, nor can you declare one static or at file scope. Neither can you explicitly initialize a VLA.
I recently started programming C just for fun. I'm a very skilled programmer in C# .NET and Java within the desktop realm, but this is turning out to be a bit too much of a challenge for me.
I am trying to do something as "simple" as returning a two-dimensional array from a function. I've tried researching on the web for this, but it was hard for me to find something that worked.
Here's what I have so far. It doesn't quite return the array, it just populates one. But even that won't compile (I am sure the reasons must be obvious to you, if you're a skilled C programmer).
void new_array (int x[n][n]) {
int i,o;
for (i=0; i<n; i++) {
for (o=0; o<n; o++) {
x[i][o]=(rand() % n)-n/2;
}
}
return x;
}
And usage:
int x[n][n];
new_array(x);
What am I doing wrong? It should be mentioned that n is a constant that has the value 3.
Edit: Here's a compiler error when trying to define the constant: http://i.imgur.com/sa4JkXs.png
C does not treat arrays like most languages; you'll need to understand the following concepts if you want to work with arrays in C.
Except when it is the operand of the sizeof or unary & operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array. This result is not an lvalue; it cannot be the target of an assignment, nor can it be an operand to the ++ or -- operators.
This is why you can't define a function to return an array type; the array expression will be converted to a pointer type as part of the return statement, and besides, there's no way to assign the result to another array expression anyway.
Believe it or not, there's a solid technical reason for this; when he was initially developing C, Dennis Ritchie borrowed a lot of concepts from the B programming language. B was a "typeless" language; everything was stored as an unsigned word, or "cell". Memory was seen as a linear array of "cells". When you declared an array as
auto arr[N];
B would set aside N "cells" for the array contents, along with an additional cell bound to arr to store the offset to the first element (basically a pointer, but without any type semantics). Array accesses were defined as *(arr+i); you offset i cells from the address stored in a and dereferenced the result. This worked great for C, until Ritchie started adding struct types to the language. He wanted the contents of the struct to not only describe the data in abstract terms, but to physically represent the bits. The example he used was something like
struct {
int node;
char name[14];
};
He wanted to set aside 2 bytes for the node, immediately followed by 14 bytes for the name element. And he wanted an array of such structures to be laid out such that you had 2 bytes followed by 14 bytes followed by 2 bytes followed by 14 bytes, etc. He couldn't figure out a good way to deal with the array pointer, so he got rid of it entirely. Rather than setting aside storage for the pointer, C simply calculates it from the array expression itself. This is why you can't assign anything to an array expression; there's nothing to assign the value to.
So, how do you return a 2D array from a function?
You don't. You can return a pointer to a 2D array, such as:
T (*func1(int rows))[N]
{
T (*ap)[N] = malloc( sizeof *ap * rows );
return ap;
}
The downside to this approach is that N must be known at compile time.
If you're using a C99 compiler or a C2011 compiler that supports variable-length arrays, you could do something like the following:
void func2( size_t rows, size_t cols, int (**app)[cols] )
{
*app = malloc( sizeof **app * rows );
(*app)[i][j] = ...; // the parens are necessary
...
}
If you don't have variable-length arrays available, then at least the column dimension must be a compile-time constant:
#define COLS ...
...
void func3( size_t rows, int (**app)[COLS] )
{
*app = malloc( sizeof **app * rows );
(*app)[i][j] = ...;
}
You can allocate memory piecemeal into something that acts like a 2D array, but the rows won't necessarily be contiguous:
int **func4( size_t rows, size_t cols )
{
int **p = malloc( sizeof *p * rows );
if ( p )
{
for ( size_t i = 0; i < rows; i++ )
{
p[i] = malloc( sizeof *p[i] * cols );
}
}
return p;
}
p is not an array; it points to a series of pointers to int. For all practical purposes, you can use this as though it were a 2D array:
int **arr = foo( rows, cols );
...
arr[i][j] = ...;
printf( "value = %d\n", arr[k][l] );
Note that C doesn't have any garbage collection; you're responsible for cleaning up your own messes. In the first three cases, it's simple:
int (*arr1)[N] = func(rows);
// use arr[i][j];
...
free( arr1 );
int (*arr2)[cols];
func2( rows, cols, &arr2 );
...
free( arr2 );
int (*arr3)[N];
func3( rows, &arr3 );
...
free( arr3 );
In the last case, since you did a two-step allocation, you need to do a two-step deallocation:
int **arr4 = func4( rows, cols );
...
for (i = 0; i < rows; i++ )
free( arr4[i] )
free( arr4)
Your function return void, so the return x; line is superfluous. Aside from that, your code looks fine. That is, assuming you have #define n 3 someplace and not something like const int n = 3;.
You can't return an array in C, multidimensional or otherwise.
The main reason for this is that the language says you can't. Another reason would be that generally local arrays are allocated on the stack, and consequently deallocated when the function returns, so it wouldn't make sense to return them.
Passing a pointer to the array in and modifying it is generally the way to go.
To return (a pointer to) a newly-created array of dimensions known at compile time, you can do this:
#define n 10 // Or other size.
int (*new_array(void))[n]
{
int (*x)[n] = malloc(n * sizeof *x);
if (!result)
HandleErrorHere;
for (int i = 0; i < n; ++i)
for (int o = 0; i < n; ++o)
x[i][o] = InitialValues;
return x;
}
…
// In the calling function:
int (*x)[n] = new_array();
…
// When done with the array:
free(x);
If the size is not known at compile time, you cannot even return a pointer to an array. C does support variable-length arrays but not in the return types of functions. You could instead return a pointer to a variable-length array through a parameter. That requires using a parameter that is a pointer to a pointer to an array of variable length, so it gets somewhat messy.
Also, the preferred choices between allocating an array in the caller dynamically, allocating an array in the caller automatically, allocating an array in the called function dynamically and using variable-lengths arrays or fixed-length arrays or even one-dimensional arrays with manual indexing depend on context, including what how large the array might be, how long it will live, and what operations you intend to use it for. So you would need to provide additional guidance before a specific recommendation could be made.
In C there's only pass/return by value (no pass by reference). Thus the only way of passing the array (by value) is to pass its address to the function, so that it can manipulate it through a pointer.
However, returning by value an array's address isn't possible, since by the time control reaches the caller, the function goes out of scope and its automatic variables go down with it too. Hence if you really have to, you can dynamically allocate the array, populate and return it, but the preferred method is passing the array and leaving the onus of maintaining the array to the caller.
As for the error, the only warning I get in GCC for this is warning: 'return' with a value, in function returning void which is simply meaning that you shouldn't return anything from a void function.
void new_array (int x[n][n]); what you're really doing here is taking a pointer to an array of n integers; the decayed type is int (*x)[n]. This happens because arrays decay into pointers generally. If you know n at compile time, perhaps the best way to pass is:
#define n 3
void new_array (int (*x)[n][n]) {
int i,o;
for (i=0; i<n; i++) {
for (o=0; o<n; o++) {
x[i][o]=(rand() % n)-n/2;
}
}
}
And call it as
int arr[n][n];
new_array(&arr);
You can pass around arbitrarily dimensions arrays like any another variable if you wrap them up in a struct:
#include <stdio.h>
#define n 3
struct S {
int a[n][n];
};
static struct S make_s(void)
{
struct S s;
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
s.a[i][j] = i + j;
}
return s;
}
static void print_s(struct S s)
{
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf(" %d", s.a[i][j]);
printf("\n");
}
}
int main(void) {
struct S s;
s = make_s();
print_s(s);
return 0;
}
You are probably declaring n as a constant integer:
const int n = 3;
Instead, you should define n as a preprocessor definition:
#define n 3
Say I have an array: array[2][4], and inside the main method, I have a call to a function blackandwhite. How can I pass this method the length and width of the array as arguments?
This is a possible solution :
void blackandwhite(int* array, int height, int width)
{
// Array-processing done here.
// array is pointer to int,
// initially points to element myarray[0][0].
// variable height = 2;
// variable width = 4;
}
int main()
{
int myarray[2][4];
blackandwhite(&myarray[0][0], 2, 4);
}
One can find the size of an array i.e. the number of elements in it by the following construct :
int array[8];
int size = sizeof(array)/sizeof(array[0]);
Unfortunately, C arrays are native arrays and do NOT contain any metadata embedded in them. Rows and Columns are just a way of representing/accessing what is essentially linear storage space in memory. AFAIK, there is no way to automatically determine the number of rows/columns of a 2D-array, given a pointer to it (in C).
Hence one needs to pass the number of columns/rows as separate arguments along-with the pointer to the 2D-array as shown in the example above.
More info on a related question here.
UPDATE:
Common pitfall no.1 : Using int** array in param-list
Note that a pointer to a 2 dimensional array of integers is still a pointer to a int.
int** implies that the param refers to a pointer to a pointer to an int, which is NOT the case here.
Common pitfall no.2 : Using int[][] in param-list
Failing to pass the dimension(s) of the array. One need NOT pass the size of the array's 1st dimension (but you may but the compiler will ignore it). The trailing dimensions are compulsory though. So,
// is INVALID!
void blackandwhite(int array[][], int height, int width)
// is VALID, 2 is ignored.
void blackandwhite(int array[2][4], int height, int width)
// is VALID.
void blackandwhite(int array[][4], int height, int width)
If you are using a C99 compiler, or a C2011 compiler that supports variable-length arrays, you can do something like the following:
/**
* the cols parameter must be declared before it is used in
* the array parameter.
*/
void blackandwhite(size_t rows, size_t cols, int (*array)[cols])
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
array[i][j] = ...;
}
and you would call it as
int array[N][M];
...
blackandwhite(N, M, array);
In most cases1, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element in the array. The expression array has type "N-element array of M-element array of int"; when we pass it as a parameter to blackandwhite, it's converted to an expression of type "pointer to M-element array of int", or int (*)[M], and its value is the same as &array[0].
If you are using a C2011 compiler that doesn't support variable-length arrays (VLA support is now optional), or a C89 or earlier compiler (which never supported VLAs), then you have two choices: you can either hardcode the number of columns:
void blackandwhite(size_t rows, int (*array)[M])
{
size_t i,j;
for (i = 0; i < rows; i++)
for (j = 0; j < M; j++)
array[i][j] = ...;
}
...
blackandwhite(N, array);
in which case this function will only work with arrays that have a specific number of columns, or you can use the approach shown by theCodeArtist, where you explicitly pass a pointer to the first element of the array along with the rows and columns as parameters. However, this means that you'll be treating array as a 1D array, not a 2D array, meaning you'll have to map 2D indices onto a 1D structure:
void blackandwhite(int *array, size_t rows, size_t cols)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
array[i * rows + j] = ...; // use a 1D index
}
...
blackandwhite(&array[0][0], N, M);
Note that this approach relies on all the rows and columns of array being contiguous in memory; if you had dynamically allocated array such that
int **array = malloc(N * sizeof *array);
if (array)
{
size_t i;
for (i = 0; i < N; i++)
array[i] = malloc(M * sizeof *array[i]);
}
then there's no guarantee that rows are laid out contiguously in memory. However, in this specific case, you could write the following:
void blackandwhite(int **array, size_t rows, size_t cols)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
array[i][j] = ...;
}
...
blackandwhite(array, N, M);
Confused yet?
Remember that the expression a[i] is treated as *(a + i); that is, we find the address of the ith element after a and dereference the resulting pointer value. a[i][j] is interpreted as *(*(a+i)+j); *(a + i) gives us the i'th array following a; by the rule mentioned above, this expression is converted from array type to pointer type, and the value is the address of the first element. We then add j to the new pointer value and dereference the result again.
We can use array[i][j] where array is passed as either a pointer to an array (int (*array)[cols] or int (*array)[M]) or as a pointer to pointer (int **array) because the result of array[i] is either a pointer type or an array type that decays to a pointer type, which can have the subscript operator applied to it. We can't use array[i][j] where array is passed as a simple pointer to int, because in that case the result of array[i] is not a pointer type.
So why not do
void blackandwhite(int **array, size_t rows, size_t cols) {...}
...
int array[N][M];
blackandwhite((int **) array, N, M);
Pointers and arrays are different things, so a pointer to a pointer and a pointer to an array are different things. That would probably work, but you're lying to the compiler. Above everything else, it's bad form.
EDIT
In the context of a function parameter declaration, a parameter declaration of the form T a[] or T a[N] will be interpreted as T *a; IOW, a will be declared as a pointer, not an array. Similarly, parameter declarations of the form T a[N][M] or T a[][M] are treated as T (*a)[M]; again, a is declared as a pointer, not an array.
In our first example we could have declared blackandwhite as
void blackandwhite(size_t rows, size_t cols, int array[rows][cols])
or
void blackandwhite(size_t rows, size_t cols, int array[][cols])
but I prefer using pointer declarations explicitly, since it correctly reflects what's happening.
1. The exceptions to this rule are when the array expression is an operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize another array in a declaration, such as
char str[]="This is a test";.
In C, it is known that there is a method to calculate length of a string whereas in the case of array, you have to explicitly specify the dimensions of the array for passing length and width to the function blackandwhite.
I am new to C programming and this is my problem:
I want to store the first value of each array in a new array, then the second value of each array in a new array and so on.
I could declare the array of pointers but I don't know how I use it!
Please I need Help.
int main()
{
int t1[4]={0,1,2,3};
int t2[4]={4,5,6,7};
int t3[4]={8,9,10,11};
int t4[4]={12,13,14,15};
int *tab[4]={t1,t2,t3,t4};
int i,j,k,l;
for (i=0; i<4;i++)
{
printf("%d\t", *tab[i]);
}
return 0;
}
When I do this, I store just the first value of each array.
Your terminology is a little bit all over the place. I think the easiest way to answer your question is to go through your code line by line.
int main()
{
int t1[4]={0,1,2,3}; //Declares a 4 integer array "0,1,2,3"
int t2[4]={4,5,6,7}; //Declares a 4 integer array "4,5,6,7"
int t3[4]={8,9,10,11}; //Declares a 4 integer array "8,9,10,11"
int t4[4]={12,13,14,15}; //Declares a 4 integer array "12,13,14,15"
int *tab[4]={t1,t2,t3,t4};//Declares a 4 pointer of integers array "address of the first element of t1, address of the first element of t2, ..."
int i,j,k,l; //Declares 4 integer variables: i,j,k,l
for (i=0; i<4;i++)
{
printf("%d\t", *tab[i]); //print out the integer that is pointed to by the i-th pointer in the tab array (i.e. t1[0], t2[0], t3[0], t4[0])
}
return 0;
}
Everything you are doing seems ok until your loop. You are showing only the first integer of every array because you are not going through them. To iterate over them, your code should look like this:
for (i=0; i<4;i++)
{
for (j=0; j<4; j++)
{
printf("%d\t", *(tab[j] + i));
}
}
The above code uses two loop counters, one (the i) to go through the positions in the array (first value in the array, second value in the array, etc.); the other to go through the different arrays (the j). It does this by retrieving the pointer stored in tab[j] and creating a new pointer that has the right offset to show the value for the ith column. This is called pointer arithmetic (there is additional information about pointer arithmetic here)
Most people find the syntax *(tab[j] + i) to be clunky, but it is more descriptive of what is actually happening. In C, you can rewrite it as tab[j][i], which is much more usual.
You have stored the data as you intended, you just need to access it properly
for (i=0; i<4;i++)
{
for (j = 0; j < 4; j++) {
int* temp = tab[i];
printf("%d\t", temp[j]); // or try the next line...
printf("%d\t", *(temp + j)); // prints same value as above line
printf("%d\t", tab[i][j]; // the same value printed again
}
}
All of the above print the same value, it is just different ways of accessing that value using pointer arithmetic. Each element of tab is a int* the value of each is the address of your other defined int[] arrays at the start
Edit: In response to the comment of Jerome, you can achieve that by declaring 4 arrays
int tab1[4]={*t1,*t2,*t3,*t4};
int tab2[4]={*(t1+1),*(t2+1),*(t3+1),*(t4+1)};
int tab3[4]={*(t1+2),*(t2+2),*(t3+2),*(t4+2)};
int tab4[4]={*(t1+3),*(t2+3),*(t3+3),*(t4+3)};
Now tab1 contains the first elements of each array, tab2 the second elements, and so on.
Then you can use
int *tttt[4]={tab1,tab2,tab3,tab4};
for (i=0; i<4;i++) {
for (j = 0; j < 4; j++) {
printf("%d\t", tttt[i][j]);
}
}
to print what you wanted. If you declared another pointer array like you did at the start
int* tab[4] = {t1,t2,t3,t4};
then essentially in matrix terms, tttt is the transpose of tab
You store everything but you just don't show it. Try
for (i=0; i<4;i++)
{
for (j=0; j<4; j++)
printf("%d\t", *(tab[i]+j));
}
int* (*a[5])[5][5][5] declares an array of 5 pointers to a 3d array of pointers to ints
int* (*(*a[5])[5])[5][5][5] declares an array of 5 pointers to an array of 5 pointers to a 3d array of pointers to ints.
#include <stdio.h>
int main()
{
int t1[4]={0,1,2,3};
int t2[4]={4,5,6,7};
int t3[4]={8,9,10,11};
int t4[4]={12,13,14,15};
int (*tab[4])[4]={&t1,&t2,&t3,&t4};
int i,j,k,l;
for (i=0; i<4;i++)
{
printf("%d\t", (*tab[i])[1]);
}
return 0;
}
There's a difference between t2 and &t2. Though they have the same value their types are different. int [4] vs int (*)[4]. The compiler will throw a warning (clang) or error (gcc).
int a[4] is conceptually at compiler level a pointer to an array of 4 as well as being the array itself (&a == a).
int (*a)[4] is conceptually at compiler level a pointer to a pointer to an array of 4 as well as being a pointer to the array itself (a == *a) because it's pointing to an array type where the above is true.
At runtime, if an int * and int (*a)[4] point to the same address, they are physically identical – it's just an address, the same address. The type only matters in how the compiler interprets and produces arithmetic operations with that address and the assembly it actually outputs based on the type. You can cast the address to any type you want in order to achieve the desired code output to manipulate data at the address it holds. An int a[4] type however is physically the array itself but you use it as if there is a pointer a to it in memory which is given the same address as the array itself. A pointer to int a[4] means 'a pointer to the address range a that is treated by the compiler as an array with int element width, where the compiler treats the start of the array as if it were a pointer to the array', and any operations on that type will be consistent in a derefernce chain i.e. you must at compiler level use (*a)[0] to access the first element if the type is a pointer to an array, but if you cast the same address to int * then you need to use a[0] to access the member.