Well, pointer arithmetic honors the data type!!

iterator = ds + 5;

will get the job done.

To elaborate, the above expression will produce a pointer by moving it 5 times, multiplied by the size of type for ds, in bytes. That's the same as &(ds[5]).

For sake of completeness, explaining why iterator = ds + (sizeof(dummy_struct)*5); is wrong, is, here, you're essentially trying to move the pointer to an element with index as (sizeof(dummy_struct)*5 which is, well out of bounds. Note please, this invokes undefined behavior!! note below

Quoting C11, chapter §6.5.6/P8

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. [....]

and then, regarding the undefined behavior mentioned above,

[....] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.


That being said, the printf() statement is also erroneous. You have two conversion specifiers, but supplied three arguments. It's not harmful, but useless/meaningless.

Related, from chapter §7.21.6.1/P2,

[...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. [...]

Based on this case, you can directly use

printf("5th position %d:%s:\n",ds[5].id,ds[5].buffer);
Answer from Sourav Ghosh on Stack Overflow
Top answer
1 of 3
30

Well, pointer arithmetic honors the data type!!

iterator = ds + 5;

will get the job done.

To elaborate, the above expression will produce a pointer by moving it 5 times, multiplied by the size of type for ds, in bytes. That's the same as &(ds[5]).

For sake of completeness, explaining why iterator = ds + (sizeof(dummy_struct)*5); is wrong, is, here, you're essentially trying to move the pointer to an element with index as (sizeof(dummy_struct)*5 which is, well out of bounds. Note please, this invokes undefined behavior!! note below

Quoting C11, chapter §6.5.6/P8

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. [....]

and then, regarding the undefined behavior mentioned above,

[....] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.


That being said, the printf() statement is also erroneous. You have two conversion specifiers, but supplied three arguments. It's not harmful, but useless/meaningless.

Related, from chapter §7.21.6.1/P2,

[...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. [...]

Based on this case, you can directly use

printf("5th position %d:%s:\n",ds[5].id,ds[5].buffer);
2 of 3
8

The behaviour of

iterator = ds + (sizeof(dummy_struct) * 5);

is undefined if you set a pointer beyond one past the final element of the array. You are actually setting iterator to further elements in the array than you think, by a factor of sizeof(dummy_struct)! Don't do that.

The language allows you to use the notation iterator = ds + 5;. This idiomatic pointer arithmetic adds 5 lots of sizeof(dummy_struct) to the address iterator. In other words the compiler does the sizeof adjustment for you. That's one reason why pointer arithmetic is so powerful.

Finally note that *(ds + 5) is equivalent to ds[5]. I find the latter affords more clarity when working with arrays.

🌐
Learn C
learn-c.org › en › Pointer_Arithmetics
Pointer Arithmetics - Learn C - Free Interactive C Tutorial
#include <stdio.h> int main() { int intarray[5] = {10,20,30,40,50}; int i; for(i = 0; i < 5; i++) printf("intarray[%d] has value %d - and address @ %x\n", i, intarray[i], &intarray[i]); int *intpointer = &intarray[3]; //point to the 4th element in the array printf("address: %x - has value %d\n", intpointer, *intpointer); //print the address of the 4th element intpointer++; //now increase the pointer's address so it points to the 5th elemnt in the array printf("address: %x - has value %d\n", intpointer, *intpointer); //print the address of the 5th element return 0; }
Discussions

Move pointer in arrays with C - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Is there anyway I can move the pointer in the array. So, like you move where the pointer is pointing at in the array. More on stackoverflow.com
🌐 stackoverflow.com
how to move file pointer to a particular line in c
Hello experts, I ve a text file I want to go to particular line . what is the best way to do this in c ? I am tried as follows fseek ( fh, pos, SEEK_SET); but this functions moves the file pointer according to a number of bytes. Unfortunately I don't know the exact byte of the desired pointer ... More on unix.com
🌐 unix.com
7
0
October 18, 2017
using a function to move a pointer(I thi - C++ Forum
I was under the impression that if I passed pointer to a function the change would persist in main. Thanks for reading. ps. I know I should have used definitions and stuff but I'm just trying to get this working at the moment. More on cplusplus.com
🌐 cplusplus.com
February 25, 2010
c - How to increment a pointer address and pointer's value? - Stack Overflow
Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array. ... ptr++; // Pointer moves to the next int position (as if it was an array) ++ptr; // Pointer moves to the next int position ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/c_programming › moving array pointer question
r/C_Programming on Reddit: Moving array pointer question
August 20, 2022 -

Im wondering why if I moved the pointer of str_out to the end, thus not being able to print the string with ` printf("%s", str_out)` in remove_exclamation(), how come I can do ` printf("%s", str_out)` in the main ().

#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>

void remove_exclamation_marks(const char *str_in, char *str_out) {
    char *point = str_out;
    while (*str_in) {
        if(*str_in != '!')
            *str_out++ = *str_in;
        str_in++;
    }
    *str_out = '\0';
    printf("%s", str_out); // doesnt print anything bc pointer pointing at the \0
    printf("%s", point); // begin of str_out
}

int main() {
    char str_in [] = "Hello W!orld!!";
    char str_out [strlen(str_in)];
    remove_exclamation_marks(str_in, str_out);
    printf("%s", str_out);
}

🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 43561-how-do-i-move-pointer.html
How do I move a pointer?
August 17, 2003 - Eg. If you "data area" is a char array, setup the pointer like this: char *pData; and if it's an array of ints... int *pData; Note: Incrementing a pointer by 1 in these cases will advance to the next element, not the next byte, so...
🌐
UAF
cs.uaf.edu › 2010 › spring › cs202 › lecture › 01_28_pointers.html
Pointers and Pointer Arithmetic
cout<<*p++; print the thing the pointer is pointing at, then move the pointer forwards (dereference, print, and increment). if (p==q) ...: compare two pointers, to see if they're pointing at the same place in memory.
🌐
UAF
cs.uaf.edu › 2009 › fall › cs301 › lecture › 09_23_pointers.html
Pointers, Pointer Arithmetic, and Messy Uncertain Death
You can do pointer arithmetic to move your pointer around, either by just modifying the register (as in rcx below), or by folding the new address into the memory access as an "offset" (as in the "DWORD [rax + 16]" below): mov edi, 40; malloc's first (and only) parameter: number of bytes to ...
🌐
Quora
quora.com › How-do-you-move-a-file-pointer-to-a-particular-line-in-C
How to move a file pointer to a particular line in C - Quora
Answer (1 of 3): Particular line…. Mmmm… imposible Because text files don’t have a fixed length per line you can run over the file with fgets and count the number of lines until reach the one you want or eof is reached There is a function called fseek (or similar) that lets you move to an speci...
Find elsewhere
🌐
Florida State University
cs.fsu.edu › ~myers › cgs4406 › notes › pointers.html
Pointer Basics and Pass-By-Address
In the above array example, we referred to an array item with p[6]. We could also say *(p+6). When you add to a pointer, you do not add the literal number. You add that number of units, where a unit is the type being pointed to. For instance, p + 6 in the above example means to move the pointer forward 6 integer addresses.
🌐
Unix.com
unix.com › applications › programming
how to move file pointer to a particular line in c - Programming - Unix Linux Community
October 18, 2017 - Hello experts, I ve a text file I want to go to particular line . what is the best way to do this in c ? I am tried as follows fseek ( fh, pos, SEEK_SET); but this functions moves the file pointer according t…
🌐
Cplusplus
cplusplus.com › forum › beginner › 20121
using a function to move a pointer(I thi - C++ Forum
February 25, 2010 - @Slambofett: thank you for your suggestion but I don't think I explained the symptoms of my problem in enough detail. the pointer p was marking the square correctly but the pointer itself was returning to the centre at the start of every go. I was ending up with something like this at the end of 4 trys ****** **?*** *?*?** **?*** ****** you got me thinking though, about where the pointer move was being implemented so I decided to scrap the entire "move" function and I placed it's code in main, inside the infinite loop.
🌐
Gitbooks
pebble.gitbooks.io › learning-c-with-pebble › content › chapter08.html
Chapter 8: Pointers and Memory Allocation · Learning C with Pebble
We have also seen how to use pointer arithmetic to move pointers through allocated memory space. As declared and initialized to a memory space, pointers point to the base, the first element, of that space. This is item number 0 in array notation. Whenever we add 1 to a pointer, the system computes the size, in bytes, of the data type that the pointer points to and increments that pointer the number of bytes that make up that data type.
🌐
freeCodeCamp
freecodecamp.org › news › pointers-in-c-programming
How to Use Pointers in C Programming
May 3, 2023 - For example, we can increment a pointer to move it to the next memory location.
Top answer
1 of 5
272

First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.

Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.

Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.

So, to sum it all up:

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value pointed at by ptr is incremented
++(*ptr); // The value pointed at by ptr is incremented
++*(ptr); // The value pointed at by ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value pointed at by ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then gets accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then gets accessed, with your code, segfault

As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.

EDIT:

So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence

2 of 5
18

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value
🌐
Dartmouth College
cs.dartmouth.edu › ~campbell › cs50 › pointers.html
Pesky Pointers
Here we require the memory address of the variables i and j before passing these addresses to the swap() function. Notice, that we are still using pass-by-value parameter passing, but that we are passing addresses on the run-time stack. The two asterisks * in swap()’s formal definition (e.g., ...
🌐
Florida State University
cs.fsu.edu › ~myers › c++ › notes › pointers2.html
Pointer Basics
In the above array example, we referred to an array item with p[6]. We could also say *(p+6). When you add to a pointer, you do not add the literal number. You add that number of units, where a unit is the type being pointed to. For instance, p + 6 in the above example means to move the pointer forward 6 integer addresses.
🌐
Embedded
embedded.com › home › best practices to safely navigate pointers in c/c++
Best practices to safely navigate pointers in C/C++ - Embedded
August 26, 2024 - Thus, understanding how pointers work is the first step in safely navigating their usage. ... This declaration does not allocate memory for an integer; it merely creates a pointer that can point to an integer’s memory location. It’s important to initialize pointers before using them, as using an uninitialized pointer can lead to undefined behavior.
🌐
CodeProject
codeproject.com › Articles › 5344758 › Using-Cplusplus-Move-Semantics-to-Manage-Pointers
Using C++ Move Semantics to Manage Pointers to Externally Allocated Memory - CodeProject
The win32 subsystem often returns pointers to objects that need to be deallocated by the caller. In this article, I show a way to do this reliably and in an exc