通过将指针更改为更高的索引可以缩小 C 中的数组吗?
Is it ok to shrink an array in C by changing the pointer to a higher index?
例如,如果我有:
char arr[] = "this is a test";
但我决定将其缩小 5,所以我这样做:
arr = &arr[5]:
我试过了,它似乎工作正常,我只是想知道这是否会导致任何未定义的行为或 "memory issues"。
不,这段代码甚至无法编译。它给出了这个错误信息:
error: assignment to expression with array type
arr = &arr[5];
^
你可以做的是:
char arr[] = "this is a test";
char *ptr = arr;
printf("Before: %s\n", ptr);
ptr = &arr[5];
printf("After: %s\n", ptr);
这是否是个好主意取决于具体情况。由于数组是在堆栈上分配的,因此非常安全。不会导致内存泄漏。
这里有一个关于这个主题的有趣的绕口令。这样写怎么样?
char * arr = "this is a test";
那你有一个指针,没有数组,对吧?好吧,这段代码确实允许您执行重新分配 arr = &arr[5]
。但是,这不等同于:
char str[] = "this is a test";
char * arr = malloc(strlen(str));
strcpy(arr, str);
它等同于:
static char _unnamed_[] = "this is a test";
char * arr = _unnamed_;
这两者之间的一个区别是您是否从函数返回 arr
。另一个是如果你在上面调用 free
。
数组与指针
在评论你的post你"thought that an array name was essentially identical to a pointer",这是错误的。犯这个错误很容易,我已经犯过数千次了,在 SO 上我也曾在这件事上有过应有的贡献。但是数组不是指针。但是,在许多情况下,数组确实 衰减 到指针,这正是上面行 char *ptr = arr
中发生的情况。
关于这个有很多问题和有启发性的答案。这是两个:
What is the difference between char array vs char pointer in C?
Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?
实际上,数组衰减为指针也是ptr = &arr[5]
行上发生的事情。根据 []
运算符的定义,这与编写 ptr = &(*(arr + 5))
相同
Why is a[5]
the same as 5[a]
?
例如,如果我有:
char arr[] = "this is a test";
但我决定将其缩小 5,所以我这样做:
arr = &arr[5]:
我试过了,它似乎工作正常,我只是想知道这是否会导致任何未定义的行为或 "memory issues"。
不,这段代码甚至无法编译。它给出了这个错误信息:
error: assignment to expression with array type
arr = &arr[5];
^
你可以做的是:
char arr[] = "this is a test";
char *ptr = arr;
printf("Before: %s\n", ptr);
ptr = &arr[5];
printf("After: %s\n", ptr);
这是否是个好主意取决于具体情况。由于数组是在堆栈上分配的,因此非常安全。不会导致内存泄漏。
这里有一个关于这个主题的有趣的绕口令。这样写怎么样?
char * arr = "this is a test";
那你有一个指针,没有数组,对吧?好吧,这段代码确实允许您执行重新分配 arr = &arr[5]
。但是,这不等同于:
char str[] = "this is a test";
char * arr = malloc(strlen(str));
strcpy(arr, str);
它等同于:
static char _unnamed_[] = "this is a test";
char * arr = _unnamed_;
这两者之间的一个区别是您是否从函数返回 arr
。另一个是如果你在上面调用 free
。
数组与指针
在评论你的post你"thought that an array name was essentially identical to a pointer",这是错误的。犯这个错误很容易,我已经犯过数千次了,在 SO 上我也曾在这件事上有过应有的贡献。但是数组不是指针。但是,在许多情况下,数组确实 衰减 到指针,这正是上面行 char *ptr = arr
中发生的情况。
关于这个有很多问题和有启发性的答案。这是两个:
What is the difference between char array vs char pointer in C?
Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?
实际上,数组衰减为指针也是ptr = &arr[5]
行上发生的事情。根据 []
运算符的定义,这与编写 ptr = &(*(arr + 5))
Why is a[5]
the same as 5[a]
?