mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 09:41:36 +00:00
Update c.html.markdown
Added additional info on dynamically allocated arrays in C.
This commit is contained in:
parent
66bc42e31b
commit
2acf7822bd
@ -445,6 +445,17 @@ int main (int argc, char** argv)
|
|||||||
for (xx = 0; xx < 20; xx++) {
|
for (xx = 0; xx < 20; xx++) {
|
||||||
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
|
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
|
||||||
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
|
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
|
||||||
|
|
||||||
|
// Note that there is no standard way to get the length of a
|
||||||
|
// dynamically allocated array in C. Because of this, if your arrays are
|
||||||
|
// going to be passed around your program a lot, you need another variable
|
||||||
|
// to keep track of the number of elements (size) of an array. See the
|
||||||
|
// functions section for more info.
|
||||||
|
int size = 10;
|
||||||
|
int *my_arr = malloc(sizeof(int) * size);
|
||||||
|
// Add an element to the array
|
||||||
|
my_arr = realloc(my_arr, ++size);
|
||||||
|
my_arr[10] = 5;
|
||||||
|
|
||||||
// Dereferencing memory that you haven't allocated gives
|
// Dereferencing memory that you haven't allocated gives
|
||||||
// "unpredictable results" - the program is said to invoke "undefined behavior"
|
// "unpredictable results" - the program is said to invoke "undefined behavior"
|
||||||
@ -530,6 +541,23 @@ swapTwoNumbers(&first, &second);
|
|||||||
printf("first: %d\nsecond: %d\n", first, second);
|
printf("first: %d\nsecond: %d\n", first, second);
|
||||||
// values will be swapped
|
// values will be swapped
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
With regards to arrays, they will always be passed to functions
|
||||||
|
as pointers. Even if you statically allocate an array like `arr[10]`,
|
||||||
|
it still gets passed as a pointer to the first element in any function calls.
|
||||||
|
Again, there is no standard way to get the size of a dynamically allocated
|
||||||
|
array in C.
|
||||||
|
*/
|
||||||
|
// Size must be passed!
|
||||||
|
// Otherwise, this function has no way of knowing how big the array is.
|
||||||
|
void printIntArray(int *arr, int size) {
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < size; i++) {
|
||||||
|
printf("arr[%d] is: %d\n", i, arr[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// if referring to external variables outside function, must use extern keyword.
|
// if referring to external variables outside function, must use extern keyword.
|
||||||
int i = 0;
|
int i = 0;
|
||||||
void testFunc() {
|
void testFunc() {
|
||||||
|
Loading…
Reference in New Issue
Block a user