As function arguments, passing multidimensional arrays in C. In C, passing multidimensional arrays are no longer used and can be used as function arguments (again in a code library) in C. The examples below illustrate this.
typedef struct {
int myint;
char* mystring;
} data;
data** array;
//initialize
int x,y,w,h;
w = 10; //width of array
h = 20; //height of array
//malloc the "y" dimension
array = malloc(sizeof(data*) * h);
//iterate over "y" dimension
for(y=0;y<h;y++){
//malloc the "x" dimension
array[y] = malloc(sizeof(data) * w);
//iterate over the "x" dimension
for(x=0;x<w;x++){
//malloc the string in the data structure
array[y][x].mystring = malloc(50); //50 chars
//initialize
array[y][x].myint = 6;
strcpy(array[y][x].mystring, "w00t");
}
}
int whatsMyInt(data** arrayPtr, int x, int y){
return arrayPtr[y][x].myint;
}
printf("My int is %d.
", whatsMyInt(array, 2, 4));
My int is 6.
Tags: c function multidimensional-array
Source: By David as answer to the question
This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 4.0
Related code-snippets:
- How do I use the C socket API in C++ on Linux?
- What's the API for GTK messagebox?
- Why am I getting double free error when I call realloc()?
- How do you format an unsigned long int using printf?
- String.indexOf in C is the most important function. It is useful for any user of C with little knowledge about C syntax.
- What are the barriers to understanding pointers?
- How to avoid redefining VERSION, PACKAGE, etc. How to avoid redefining VERSION, PACKAGE, etc.?
- What is the difference between shift operators (, >>) and logical operators in C?
- Decoding printf statements in C (Printf Primer)
- How do you calculate the size of a C file?
- How do I pass a function as a parameter in c?
- Which tool is best for makefile generation?
- How can you convert a hexadecimal string to an integer in C?
- Send messages to a program through command line.
- Do we get reading Other Process' memory in OS X?