Pointer or address?

1430 views c
-1

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

The above code is from cs50 2018 lecture #3 . t[i] = s[i] part confused me. As I know, when we say char *t , t will store the address of the first part of the memory that was allocated. So doesn't t[i] give us the address of the memory at t[i] location ? If it is like so, shouldn't we write
*t[i] = s[i] to change the value of t[i] ?

answered question

the brackets [ ] automatically dereference. t[i] is equivalent to *(t+i)

2 Answers

11

No, the [] array index operator dereferences the pointer and evaluates to the value itself, not its address. The expression s[i] is equivalent to the expression *(s + i). If you wanted the address of the element at index i, you would need to use the & operator, as in &s[i] (which is equivalent to s + i).

posted this
10

t[i] actually gives you the ith element of the array. It works the same as s[i], which has the same type.

The syntax t[i] is exactly the same as *(t + i). In other words, pointer arithmetic is performed to get a pointer to the desired element, then the result is dereferenced to get the actual element.

posted this

Have an answer?

JD

Please login first before posting an answer.