Skip to content

Instantly share code, notes, and snippets.

@shichao-an
Created March 2, 2016 07:56
Show Gist options
  • Save shichao-an/9497fd38d97760ceee5f to your computer and use it in GitHub Desktop.
Save shichao-an/9497fd38d97760ceee5f to your computer and use it in GitHub Desktop.
Arrays as function parameters in C
#include <stdio.h>
#include <stdlib.h>
/* the array name by default is a pointer to its first element,
* similar to test2
*/
void test1(int len, int x[])
{
int i;
for (i = 0; i < len; i++)
{
printf("x[%d] = %d; ", i, x[i]);
}
printf("\n");
}
/* pass the pointer to the first element */
void test2(int len, int* x)
{
for (int i = 0; i < len; i++)
{
printf("x[%d] = %d; ", i, *(x + i));
}
printf("\n");
}
/* array pointer: the array name by default points to the first element;
* &array returns the pointer to the entire array
*/
void test3(int len, int(*x)[len])
{
for (int i = 0; i < len; i++)
{
printf("x[%d] = %d; ", i, (*x)[i]);
}
printf("\n");
}
/* multidimensional array: the array name by default is a pointer to its
* first elements, which is also int(*)[]
*/
void test4(int r, int c, int y[][c])
{
for (int a = 0; a < r; a++)
{
for (int b = 0; b < c; b++)
{
printf("y[%d][%d] = %d; ", a, b, y[a][b]);
}
}
printf("\n");
}
/* multidimensional array: pass the pointer to the first element */
void test5(int r, int c, int (*y)[c])
{
for (int a = 0; a < r; a++)
{
for (int b = 0; b < c; b++)
{
printf("y[%d][%d] = %d; ", a, b, (*y)[b]);
}
y++;
}
printf("\n");
}
/* multidimensional array */
void test6(int r, int c, int (*y)[][c])
{
for (int a = 0; a < r; a++)
{
for (int b = 0; b < c; b++)
{
printf("y[%d][%d] = %d; ", a, b, (*y)[a][b]);
}
}
printf("\n");
}
/* pointer array whose elements are pointers, equivalent to test8 */
void test7(int count, char** s)
{
for (int i = 0; i < count; i++)
{
printf("%s; ", *(s++));
}
printf("\n");
}
void test8(int count, char* s[count])
{
for (int i = 0; i < count; i++)
{
printf("%s; ", s[i]);
}
printf("\n");
}
/* pointer array ending with NULL */
void test9(int** x)
{
int* p;
while ((p = *x) != NULL)
{
printf("%d; ", *p);
x++;
}
printf("\n");
}
int main(int argc, char* argv[])
{
int x[] = { 1, 2, 3 };
int len = sizeof(x) / sizeof(int);
test1(len, x);
test2(len, x);
test3(len, &x);
int y[][2] =
{
{10, 11},
{20, 21},
{30, 31}
};
int a = sizeof(y) / (sizeof(int) * 2);
int b = 2;
test4(a, b, y);
test5(a, b, y);
test6(a, b, &y);
char* s[] = { "aaa", "bbb", "ccc" };
test7(sizeof(s) / sizeof(char*), s);
test8(sizeof(s) / sizeof(char*), s);
int* xx[] = { &(int){111}, &(int){222}, &(int){333}, NULL };
test9(xx);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment