Reputation: 40140
I have some inherited code and a function which takes a character array as a parameter.
typedef char myString[256];
void MyFunc(myString param)
{
int i;
for (i = 0; i < 256; i++)
{
if (param[i] ....
I would like to make this more efficient and pass a pointer to the char array:
void MyFunc(myString *param)
{
int i;
for (i = 0; i < 256; i++)
{
if (*param[i] <========= Thsi is wrong
When I try to reference the array elements, I get the wrong value, so obviously something is wrong with my pointer dereferencing. It has been a while since I coded in C, so I can't see the obvious mistake.
Can someone please point it out?
Upvotes: 0
Views: 114
Reputation: 2582
myString *
is a pointer to a char array with 256 elements, i.e., param
has type
char (*)[256]
so you have to dereference param
first, then access its element.
param
points to.(*param)[i]
is then the ith element of the array in question.Upvotes: 2
Reputation: 121609
// This is OK: an array can be treated as "char *", and vice versa char myString[256];
void MyFunc(char * param)
{
int i;
for (i = 0; i < 256; i++)
{
if (param[i] ...
Q: I would like to make this more efficient and pass a pointer to the char array
A: There's absolutely no difference in efficiency whether you pass "param[]" or "*param"
for (i = 0; i < 256; i++)
{
if (*param[i] <==== <========= Thsi is wrong
Yup - it's wrong. Again, "param[]
" and "*param
" should be treated the same way.
Same with or without the "typedef", too :)
Finally, here's the same program with the typedef:
typedef char myString[256];
void MyFunc(myString param)
// This is treated as "MyFunc(char param[256])"
// It is *identical* to "MyFunc(char * param)"
{
int i;
for (i = 0; i < 256; i++)
{
if (param[i] ....
Upvotes: 1
Reputation: 753525
You probably don't want to pass it via a pointer; when you use the type in the argument, it becomes a pointer anyway, and second level of indirection is less efficient.
If you do use the 'pointer to an array' notation, then you need parentheses to get the precedence correct:
if ((*param)[i] ...)
...
Upvotes: 6