// Capitalizes a copy of a string while checking for errors
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Get a string
char *s = get_string("s: "); //this is in the cs50.h
char *t = malloc((strlen(s) + 1) * sizeof(char));
// Copy string into memory
for (int i = 0, n = strlen(s); i <= n; i++)
t[i] = s[i];
return 0;
}
以上代码摘自cs50 2018讲座3。部分让我困惑。我知道,当我们说
t[i] = s[i]
时,char *t
将存储分配的内存第一部分的地址。那么t
不给我们t[i]
位置的内存地址吗?如果是这样的话,我们不应该写t[i]
更改*t[i] = s[i]
的值? 最佳答案
不,[]
数组索引运算符取消对指针的引用,并计算为值本身,而不是其地址。表达式s[i]
等同于表达式*(s + i)
。如果需要索引i
处元素的地址,则需要使用&
运算符,如&s[i]
(相当于s + i
)。
int array[] = { 10, 20, 30, 40 }; // create an array for illustration
int *ptr = array; // array type decays to a pointer
// these print the same thing: the address of the array element at index 2
printf("%p\n", ptr + 2); // pointer arithmetic
printf("%p\n", &ptr[2]); // array index operator followed by address-of operator
// these print the same thing: the element at index 2 (= 30)
printf("%d\n", *(ptr + 2)); // pointer arithmetic followed by dereference operator
printf("%d\n", ptr[2]); // array index operator
关于c - 指针或地址?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53179018/