3

I have the following homework question:

Consider the following declarations and answer the question.
char strarr1[10][32];
char *strarr2[10];

Are strarr1[3][4] and strarr2[3][4] both legal references?

I tried compiling the code with gcc to test it. I was fairly sure that the second reference would throw an error, but it didn't. This is what I compiled with gcc:

int main(void){
    char strarr1[10][32];
    char *strarr2[10];

    char x = strarr1[3][4];
    char y = strarr2[3][4];

    return 0;
}

I'm working under the assumption that the test code I used is correct.

How is it possible to reference strarr2[3][4] when strarr2 is a single-dimensional array?

3 Answers 3

1

since strarr2 is an array of char*, the second [4] is an index into the char*

it means the same thing as this

char * temp = strarr2[3];
char y = temp[4];

Since I don't see anywhere in your code where strarr2 is being initialized, nor do I see anywhere that strarr2[3] is being allocated, this code will not work as presented. It will either return garbage or segfault.

Sign up to request clarification or add additional context in comments.

Comments

1

They are both legal syntax because of the pointer arithmetic indexing convention. However, in your code:

char y = strarr2[3][4];  // <--- NOT SAFE!

is accessing unallocated memory and generates undefined behavior, ergo it is bad.

So quit it.

Comments

0

It is a single dimensional array of pointers. So, you are indexing the pointer at 3 with offset=4:

char y = *(strarr2[3] + 4);

is the same as:

char y = strarr2[3][4];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.