简体   繁体   English

C指针地址分配数组

[英]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? 为什么该作业不起作用?

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 . 为有效指标lines0MAX_LINES -1

That said, as per your code, line has the scope of the loop body, outside the scope, it becomes invalid. 就是说,根据您的代码, line具有循环主体的范围,在该范围之外,它变得无效。 If you try to access the memory pointed to by the members of the lines array outside the loop, you'll invoke undefined behaviour. 如果您尝试访问循环外部lines数组的成员所指向的内存,则将调用未定义的行为。

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. 您正在为数组中的索引分配错误,并且当您需要使用分配的索引时,分配的对象将不存在,该line变量不在范围之内。 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. 当然,尽管原则上应该始终free分配的任何内容,但是编写函数分配lines并释放它是这里的最佳方法。

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. 正如其他答案所解释的那样,您正在访问数组超出范围,并且您正在分配地址,其作用域仅直到for循环为止。

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. 在这里,即使您将索引值更正为“ lines [i] = line;”,也无法使用,因为您要为每个字符指针分配相同的地址。 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(){ int main(){

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM