Berlios
Berlios

Reputation: 3

C Array of Pointers Address Assignment

#define MAX_LINES 20
#define MAX_LINE 20

int main(){

    char *lines[MAX_LINES];
    for(int i=0;i<MAX_LINES;i++){

            char line[MAX_LINE];
            lines[MAX_LINES+i]=line;

    }
}

I'm so confused why my array of pointers "lines" doesn't have any of it's addresses changed when a "line" address is assigned to it. Why isn't that assignment working?

Upvotes: 0

Views: 75

Answers (3)

Anoop Mourya
Anoop Mourya

Reputation: 26

As other answers explains that you are accessing array out of bound and you are assigning address whose scope is only till the for loop.

Coming to the main part of question "why my array of pointers "lines" doesn't have any of it's addresses changed when a "line" address is assigned to it. Why isn't that assignment working?"

Here even if you correct you index value as "lines[i]=line;", it wouldn't work as you are assigning same address to each character pointers. This is because "line" is a character array and name of the character array always points to the base of array. Try out this if your just trying to see assignment operation.

int main(){

char *lines[MAX_LINES];
char line[MAX_LINES];

for(int i=0;i<MAX_LINES;i++)
{
        lines[i]=&line[i];
}

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your code

lines[MAX_LINES+i]=line;

is pure undefined behaviour, you are trying to access array out of bounds.

The valid index for lines would be 0 to MAX_LINES -1.

That said, as per your code, line has the scope of the loop body, outside the scope, it becomes invalid. If you try to access the memory pointed to by the members of the lines array outside the loop, you'll invoke undefined behaviour.

Upvotes: 2

tadman
tadman

Reputation: 211540

You're assigning to the wrong index in your array and the thing you're assigning won't exist when you need to use it, that line variable falls out of scope. To fix that:

#define MAX_LINES 20
#define MAX_LINE 20

int main(){
  char *lines[MAX_LINES];

  for(int i=0;i<MAX_LINES;i++){
    lines[i] = malloc(MAX_LINE);
  }

  return 0;
}

Though of course you should always free anything you allocate as a matter of principle so writing a function to allocate lines as well as free it is the best approach here.

Upvotes: 2

Related Questions