Last active
August 29, 2015 14:03
-
-
Save NorrinRadd/e4f2ce9694d3b28a751c to your computer and use it in GitHub Desktop.
description of mixing pointer and array syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[18:15:43] <Chris> Norrin: it's, like all C declarations, "declaration follows use". | |
[18:16:14] <Chris> So consider char (*x)[42]; You can then reason that *x is a char[42]. And (*x)[3] is a char. | |
[18:16:46] <Chris> Norrin: and in the case of char *x[42]; you can say that x[3] is a char * and *x[3] is a char. | |
so [] has precedence over *. hence why the () are required depending on intention. | |
[18:14:32] <Chris> Norrin: char *(*a)[42]; is a pointer to array of 42 char pointers. | |
[18:18:43] <Chris> Norrin: you can also have a pointer to a variable length array though: int f(size_t s, int(*x)[s]); | |
[18:18:47] <Norrin> Chris, from anther var that tells you the size | |
[18:18:57] <Chris> Norrin: okay, sure, so put a variable in, like the above. | |
[18:23:02] <Chris> Norrin: in all C declarations, they follow the same pattern as using the objects. | |
[18:23:19] <Chris> Norrin: int x; // x is an int. | |
[18:23:24] <Chris> Norrin: int *x; // *x is an int. | |
[18:23:37] <Chris> Norrin: int *x[42]; // x[n] is an int * | |
[18:23:46] <Chris> Norrin: int (*x)[3]; // *x is an int[3] | |
[18:23:51] <Chris> This is declaration follows use. | |
[19:54:14] <Norrin> confusing that [ ] goes after identifier but * goes before it and after the target type | |
[20:32:05] <Zhivago> Just wait until you encounter something like int (*(*p)(int))[10]; | |
[20:48:09] <Sadale> int (*(*p)(int))[10] is a pointer to a function that receives and int and return a pointer to array of 10 of int? | |
[20:50:28] <Norrin> pointer to a function that returns a pointer to an int[10] | |
[20:59:04] <Norrin> how would you write p is a pointer to an array of pointers to int f(int) ? | |
[21:01:15] <Norrin> int(int)(*p)[10]? | |
[21:01:33] <Chris> int (*(*p)[10])(int) | |
[21:11:38] <Norrin> Chris, if i hadn't forgot about it being an array of pointers to the function, i would have put int*(int)(*p)[10] | |
[21:12:01] <Chris> that's a syntax error | |
[21:12:13] <Chris> (and doesn't make sense) | |
[21:19:27] <Chris> so how do you deference a function pointer? | |
[21:20:36] <Chris> Actually (*f)(params) | |
[21:20:52] <Chris> Because *f(params) is like *(f(params)) and will dereference the pointer the function returns. | |
[21:22:01] <Chris> So now you can declare function pointers the same way. | |
[21:22:45] <Chris> And this is why we declare a function returning an int * as int *f(something) | |
[21:22:51] <Chris> Because *f(something) will be an int. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment