Mawg
Mawg

Reputation: 40140

Array access, pointer confusion

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

Answers (4)

nagaradderKantesh
nagaradderKantesh

Reputation: 1690

use as below :

if (*(param +i) ...)
...

Upvotes: 0

Lei Mou
Lei Mou

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.

  1. By dereferencing param, you got the address of the first element of the array param points to.
  2. (*param)[i] is then the ith element of the array in question.

Upvotes: 2

paulsm4
paulsm4

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

Jonathan Leffler
Jonathan Leffler

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

Related Questions