I have two functions for getting the user to make a move and the computer to generate moves, so when creating a function for updating the computer and user's moves, the 'x' and 'o' for the moves and '_' for a blank space, would I use pointers for my multidimensional array and if so how would you code that? An example with an explanation would very much be appreciated!
Updating a two-dimensional char array with a function, passing the pointer to the array as a parameter:
int main(){
char array[5][5];
updateArray(array, 0, 0, 'a');
}
void updateArray(char * arr, int row, int col, char c){
arr[row][col] = c;
}
Note that when declaring an array in C, the array identifier (array in this case) is a pointer to the first element of the array. The brackets ([row][col]) access the elements of the array by calculating its address using pointer arithmetic. Hope this is helpful.
How exactly do you intend to use pointers? Pointers to what? I don't think you need pointers at all, unless you have something specific in mind that isn't stated in your question. I would use a simple two-dimensional array of chars.
Define your array like this:
char a[3][3] = {
{"_", "_", "_"},
{"_", "_", "_"},
{"_", "_", "_"}};
Your board might look like this: 4x4 multidimensional array
For example, to fill an "x" into the upper left-hand corner, write:
a[0][0] = 'x';
Hope that helps!
If you want to pass a pointer to your functions, you could declare and use it like this:
computer_move(char (*p)[3][3])
{
p[1][1] = 'x';
}
char ttt[3][3];
computer_move(&ttt);
I came across an old code where I need to allocate memory for an array of matrices. Currently it is done by creating a structure matrix and allocating memory by making an arrray of structures.
Like so.
struct matrix
{
int x[13][13];
};
int main()
{
matrix *push = (matrix*)malloc(sizeof(matrix) * 1000);
//do stuff
free(push);
return 0;
}
But now the question.. Do I really need to do this? I know I am allowed to declare a variable of type int *matrix[13][13];
But I cant seem to figure out a way to allocate memory to this variable.
I tried matrix = (int***)malloc(sizeof(int[13][13])*1000); which results in
E0137 expression must be a modifiable lvalue and honestly in doesnt seem correct either
I know there are many better and creative ways of allocating an array like this, but I am curious
Questions
int *matrix[13][13] what will this kind of variable even mean or represent? Is it a pointer to a 2D matrix or s it an pointer to an array of 2D matrices?
How will I use the above mentioned variable?
How will I allocate memory for the above variable without using any more variables?
Clarifications
From comments it seems int *matrix[13][13] represents a matrix of 13x13 int*
What I am asking is actually, is there a way to have a variable with a dynamically allocated first dimension and static 2nd and 3rd dimensions without using structures typedefs etc
EDIT
As pointed out by felix
what I am looking for is int (*matrix)[13][13] = (int(*)[13][13])malloc(1000*sizeof(matrix));
I have noticed that sometimes beginner programmers are finding typedef-ing the multidimensional matrices which have to be dynamically allocated easier as it reduces the problem to the single star pointer and the sizeof of the defined type and pointer to it is much easier to understand.
#include <stdio.h>
typedef int my13x13matrix[13][13];
int main(void) {
my13x13matrix *mylargematrix = malloc(1000 * sizeof(*mylargematrix));
mylargematrix[999][12][12] = 5;
printf("%d \n", mylargematrix[999][12][12]);
return 0;
}
you can also use the single star pointer arithmetic.
my13x13matrix *anotherpointer = &mylargematrix[10];
(*anotherpointer)[5][5] = 1;
anotherpointer++;
(*anotherpointer)[5][5] = 2;
printf("%d %d\n", mylargematrix[10][5][5], mylargematrix[11][5][5]);
No, you don't want to use
int *matrix[13][13];
That will declare a [13][13] array of int*s.
You need
// pointer to "an array of 13 x 13 ints"
int (*matrix)[13][13];
or simplify it by using a type alias.
typedef int matrix_type[13][13];
matrix_type* matrix_ptr;
You can allocate memory for such a variable using
matrix_type* matrix_ptr = malloc(1000*sizeof(*matrix_ptr));
and assign values to it using
matrix_ptr[0][0][0] = 0;
...
matrix_ptr[999][12][12] = 0;
If I have:
typedef char pos[2]; /*btw I now know no one should do this*/
void someFunction(void) {
pos *s = malloc(sizeof(pos) * 2);
}
In the cases like this how s working? What is it? Arrays are like pointers except when you use sizeof on them you will get the "correct" size. So in this case the following means that s is going to be a pointing to a sizeof(char)*4 sized memory? But the type of s is a pointer to a pointer which means that you can't use s as a one dimensional array (or a pointer which points chars ) becouse you "still need to go through one level/layer of indirection/pointer". Or am I wrong?
How can I use s? As a 2 dimensional array or as a one dimensional one?
(If you are interested: I need this bc I want to return two pos from a function. Is there a better way? (despite fixing this and using a struct for storing position data instead of a 2-sized array))
This typedef costruct is just equivalent to:
#include <stdio.h>
void someFunction(void) {
char (*pos)[2];
pos = malloc(sizeof(*pos) * 2);
pos[0][0] = 1;
}
int main(void) {
someFunction();
return 0;
}
That means that pos is the pointer to two-elements array of char. You can use just like as two-dimensional array with fixed column size as two. Number of rows is controlled by malloc() call, in your case it happened to be two as well.
I'm modifying existing code for a new project. I was instructed to remove dynamic memory allocation and use static declaration.
There is a variable arrp, earlier it was a double pointer, to which memory will be allocated using malloc and will be accessed as 2D array.
Now i have changed it as pointer to array i.e: char (*arrp)[];
The size of the 2D array to which arrp points to will be known only at runtime. My problem is if size is not declared compiler throws error('char (*)[]' : unknown size)
Please refer the following code, i did something like this
char (*arrp)[]; //This will be from different module,
//I have declared as local variable for our reference
char (*parr)[2];
char arr[3][2];
parr = &(arr[0]);
arrp = (char (*)[])&(arr[0]);
//inside loops for i, j
...
printf("%c",parr[i][j]); // This works fine
printf("%c",arrp[i][j]); // Error :'char (*)[]' : unknown size)
....
//Some code
It not possible to get the size of array when arrp is declared. Is there any way to eliminate this error?
A pointer to an array helps in jumping over whole arrays at a time. ( ie with a single increment ) It does this through the knowledge of the column width of the array to be jumped. So without the knowledge of the column size, I am afraid, your pointer to an array will be of no use to you.
But if you have a modern compiler which supports variable length arrays ( C99 ), then its quite simple
int foo ( int m, int n )
{
int a[m][n];
int (*ptr)[n]=a;
a[0][2] = 78;
printf("%d", ptr[0][2]);
}
I am making my first C program, and it utilizes a 2D array, and the code seems weird to me. First, why do I have to store "White" in [1][6]? I tried [0][6], but the compiler complains and won't run but when I call it in printf, it's [0][6]. Also, when trying to store "Bl" in codes [2][6], it says conflicting type for codes. Any help would be appreciated, thanks.
int main (int argc, const char * argv[]) {
for (q=0; q<=457; q++) {
for (w=0; w<=6; w++) {
codes[q][w] = 0;
}
}
char codes[1][6] = {'W','h','i','t','e','\0'};
char codes[2][6] = {'B','l,'\0'};
printf("%c\n", codes[0][0]);
You are confusing two tasks that you need to perform. One task is to declare a variable, and tell the compiler what type it's going to hold. The second task is to put data into it.
You are doing both tasks at the same time, and this is confusing you. In your first statement you are telling the compiler, "codes is a 2-dimensional, 1x6 array. By the way, here are the values to put into it: "White"." Your second sattement says, "codes is a 2-dimensional, 2x6 array. By the way, put "BI" into it."
The compiler is complaining and saying, "It can't be a 2x6 array, becuase you already told me it's a 1x6 array."
What you need is something like this:
char codes[2][6] = { {'W','h','i','t','e','\0'}, {'B','l,'\0'} };
You would then get your 'W' by looking at codes[0][0], etc.
You cant initalize array [0][6]
beucase this is a vector, and first
index dont have elements.
And you cant 1D (vector) array
assign to 2D array.
{'W','h','i','t','e','\0'} and
{'B','l,'\0'} is a 1D array like a
something[6] or in second case
something[3].
And you have triple declaration of
codes variable. You can only one
declare variable.
Instead of codes[0][6] if you want the compiler to decide the size of array depending on your initialization, you could say:
char codes[][6] = {'W','h','i','t','e','\0'};
if you're trying to initialize 2D array:
Try:
char codes[2][6] = {{'W','h','i','t','e'}, {'B','l'}};
Or
char codes[][6] = {{'W','h','i','t','e'}, {'B','l'}};
You're confusing initialization with assignment. You can either initialize the array when you declare it, as in
char codes[N][6] = { // where N is the total number of codes
"White", // assigns codes[0][0] - codes[0][5] as 'W','h','i','t','e',\0
"Bl", // assigns codes[1][0] - codes[1][2] as 'B','l',\0
...
};
which is equivalent to writing
char codes[N][6] = {
{'W','h','i','t','e',\0},
{'B','l',\0},
...
};
or you can assign elements of the array after the declaration, as in
char codes[N][6];
...
strcpy(codes[0], "White");
strcpy(codes[1], "Bl");
...
What you've done is munged the two together, so you're redeclaring codes with different types (the compiler is interpreting your use of [0][6] and [1][6] as array sizes, not locations), hence the compiler errors.