#Pointer problem >~>

34 messages · Page 1 of 1 (latest)

nocturne pagoda
#
long return_pointer_adress(long* pointer)
{
    long* newPointer = pointer - 2;
    long result = *newPointer;
    return result;
}```
#

used pointer arithmetic to get the address smaller by 2 * sizeof(long)

#

so im assuming you want to go back by 2 * sizeof(long)

#

then we dereference the new pointer to get the value at that address

#

nope, it doesnt work like that

#

the compiler already knows you are returning by sizeof(long), because it points to long datatype

#

to simplify things, the language already knows you are returning by 2

#

so no need to add sizeof(long)

#

// smaller by 2 * sizeof(long) than this one using pointer-specific operators. this is a trick question, ig

#

ye

#

as simple as that

#

ye

#

with n an integer, n * sizeof(long) eq to pointer - n

#

nope,

#

but whatever the size of the datatype you are using

#

the language knows it should go back by n * sizeof that datatype

#
    long* newPointer = pointer - 2;
#

because its already declared as long pointer

#

ask

#

why would you look for the hard way lol

#

well

#

sizeof(char) is 1, so it assumes the pointer is pointing to a datatype which size is 1

#

therefore you have to write 2 * sizeof(char)

#

he will, that code looks like some unsafe code even tho its safe

#

the size of char datatype is 1

#

but size of long > 1

#

prob 8 afaik

#

when working with bytes, we use char because it points to 1 size byte

#

thats why you see they cast it to (char*), char pointer

#

because if you do, you are allowed to use 2 * sizeof(char)

#

but stick to the easy way, AI does not know wether the user is a beginner or an operating system developer 😛

#

no problem, glad i helped!

hoary tide
#

the compiler adapts the increment value of a pointer according to the size of the type it points to

#
#include <stdio.h>
#include <stdlib.h>

int main(void){
  int* p = malloc(1024);
  printf("%p\n", p);
  printf("%p\n", p+1);
  return 0;
}

on most machines, the addresses will differ by 4