1

How do you pass two dimensional arrays into a function?
When I pass it, it shows up in the visual studio debugger as a single dimensional array. The problem was that when I index sel_col[i], it gets the next character, instead of the next word.

Here is my function prototype:

void print_row(char sel_col[MAX_IDENT_LEN][MAX_IDENT_LEN]);

And here is the definition of my 2d array, and where I call it:

char sel_col[MAX_NUM_COL][MAX_IDENT_LEN];
print_row(sel_col); 

Solution 1: Remove the first size identifier. Didn't work.

void print_row(char sel_col[][MAX_IDENT_LEN]);

Solution 2: Pass it by reference into the function. Didn't work.

    print_row(&sel_col); 

Solution 3: Use double pointers. I don't want to go this route, since I would rewrite most of my code.

1
  • Un-tagged C++ as this question is in C. Commented May 1, 2011 at 6:17

1 Answer 1

1

In C, two-dimensional arrays look like one dimensional arrays; a char[3][3] is really a single-dimension array just 9 elements long, and the compiler performs some math to turn two smaller indices into one bigger one. Your function prototype looks correct. What was the problem? Were you getting a compiler error?

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

5 Comments

The problem was that when I index sel_col[i], it gets the next character, instead of the next word.
You can either try a char* array[SIZE] or show us the definition of the array you're passing.
@chustar This small program works for me: codepad.org/gdcd1WKR It prints abc def ghi... on seperate lines, like you'd think it would.
I feel stupid now. I forgot to check the size of the array for situations where the passed array is less than my theoretical max.
@chustar Yeah, usually almost any time you pass an array to a function, a rule of thumb is that if you don't see the length of the array being passed to that function also, something's probably wrong. There are notable exceptions though, such as most char*s of course, but you get the idea.

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.