0
#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?

1
  • 2
    Please post a working example that demonstrates what you are asking. Commented Jun 1, 2018 at 17:20

3 Answers 3

2

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.

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

Comments

2

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.

9 Comments

I don't think this answers the question.
Not only that but adding a pointer to a variable that falls out of scope is undefined behaviour as well.
@nicomp Undefined behavior is undefined, it should be treaed with highest priority.
@tadman agree, let me update that, however, we don;t know the actual usage (print the address part), but nonetheless, it'd be invalid outside the scope.
@SouravGhosh Perhaps, but you still did not answer the OP. Your answer should be in a comment.
|
0

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];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.