3

I can imagine a two dimensional array as a contagious sequence of bytes. My question is, can it be treated as a one dimensional array with explicit cast without invoking undefined behavior?

I have tested the following code with gcc and it ran normally and didn't crash. What does the standard say about it?

int main(void)
{
    char buf[2][5];
    strcpy((char *)buf, "link 101");
    printf("%s\n", (char *)buf);
    return 0;
}

Just saying, I have good reason to think of this.

  • Fyi, "I have good reason to think it this" - that reason is likely worthy of mentioning in your question. – WhozCraig Jul 20 '16 at 22:42
  • 1
    Yes, it's compliant. See [One-dimensional access to a multidimensional array: well-defined C?](http://stackoverflow.com/questions/6290956/one-dimensional-access-to-a-multidimensional-array-well-defined-c). – dxiv Jul 20 '16 at 22:46
  • http://stackoverflow.com/questions/27093290/can-an-array-have-trailing-padding – BLUEPIXY Jul 20 '16 at 23:02
  • write `assert(sizeof(buf) == 2 * 5 * sizeof(buf[0][0]));` before do it. – BLUEPIXY Jul 20 '16 at 23:46
  • @dxiv The first two answers explain this is ub, how is this compliant? And what do you mean by 'compliant'? – 2501 Jul 21 '16 at 05:32
  • @2501 `The first two answers explain this is ub` (1) Please specify *which* ones, since the order they are listed in may/oes change with time, so *first* is meaningless. (2) If you meant the *accepted* answer, then please read to the end: `special case that should be noted: if your type were unsigned char (or any char type), accessing the multi-dimensional array as a one-dimensional array would be perfectly well-defined.`. Note that OP's question here specifically used `char`. – dxiv Jul 21 '16 at 05:43
  • @dxiv The first two by votes. Ok I agree. You didn't explain what is 'compliant' though. – 2501 Jul 21 '16 at 05:46

1 Answers1

-1

I believe, it can be treated as a 1-D array when using explicit casting.

Essentially just removing a double pointer to just one, and I believe the use of explicit casting in this form is standard.

char ** buf; //equal to char[][]
(char*) buf; //equal to char[]
Barmar
  • 741,623
  • 53
  • 500
  • 612
Omid CompSCI
  • 1,861
  • 3
  • 17
  • 29