57,318 questions
5
votes
1
answer
139
views
Why don't function pointers allow adding CV-qualifiers to pointer arguments?
I am work a mature codebase, one of the signs of its age is lack of consts which make the code difficult to reason about when refactoring.
I have found a function which takes an argument as a mutable ...
5
votes
2
answers
134
views
Error using _Generic selection to distinguish between char* and struct pointer*
I have a simple struct in C and I used typedef to create an alias (db) for it:
typedef struct {
char* name;
} db;
I then allocated memory on the heap for a pointer:
db *a = malloc(sizeof(db));
a-&...
1
vote
2
answers
201
views
Pure Type Punning In C
I want to do pure type punning without memcpy in C using pre-allocated page which I made with mmap() on Linux, because I understand the architecture and how physical ram works, alignment & ...
2
votes
1
answer
167
views
How do you replace multiple elements of an array in C with elements of a different array
If I wanted to replace large chunks of an array in C with items from another list, are there any solutions that don't involve for loops or writing code like the following?
int64_t foo[size];
foo[value]...
2
votes
3
answers
251
views
Display contents of allocated memory byte by byte? [closed]
I'm trying to display the contents of some allocated memory byte by byte:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int len;
int* vec[];
} vec_t;
int main(void) {
int ...
Advice
0
votes
3
replies
94
views
Fortran: (or other languages) how to handle a linked list with allocatables instead of pointers?
(UPDATE: after various suggestions, some solutions were added at the end. It does seem to be possible to avoid pointers altogether, but it still is not completely ideal...)
In the question Can I ...
0
votes
4
answers
166
views
heap-use-after-free when incorrectly assigning pointers during binary tree inversion [closed]
I was attempting the binary tree inversion question on Leetcode
https://leetcode.com/problems/invert-binary-tree/
I came up with this solution
TreeNode* invertTree(TreeNode* root) {
if (root ==...
1
vote
0
answers
58
views
How does i in 'scanf("%d", ptr + i);' counts to 4? [duplicate]
I mean that i is incremented by 1 right, then how does ptr + i equals ith block of memory since int size is 4?
int i, n;
printf("Enter the number of Integers: ");
scanf("%d&...
1
vote
1
answer
144
views
Why does my multithreading/pointers code print random values?
My code should print the numbers given as command line arguments. Instead it prints random-looking values.
What is going on and how can I fix it?
#include <stdio.h>
#include <pthread.h>
#...
1
vote
0
answers
61
views
Reassigning a Matlab pointer in a loop without a memory leak
We are using Matlab to communicate with a C++ library, and are struggling with memory management.
We create a libpointer pointing to an array, and then try to update its value in a loop. I don't think ...
0
votes
3
answers
101
views
Trying to read character and turn it into a string
static char* convert_to_string(const volatile uint8_t *ch)
{
static char read[40]; // static so pointer remains valid after return
uint8_t i = 0;
while (*ch != ESC || *ch != END_OF_TEXT ||...
2
votes
1
answer
217
views
Are the iterators of `map<key, value, greater<>>` and `map<key, value, less<>>` guaranteed to be the same type?
I have 2 maps
using BidBook = std::map<float, int, std::greater<>>; // price -> qty
using AskBook = std::map<float, int, std::less<>>;
I have a struct that contain iterator ...
1
vote
2
answers
176
views
Getting type of a pointer
I've created the function
void add_entry(char key[], void* value, char file[], ValueType type)
and I want to use my generic function to get the typeof the pointer
#define typeof(x) _Generic((x), \
...
0
votes
1
answer
92
views
Using std::map to look up function handlers [duplicate]
I am trying to use std::map to map numerical IDs to function handlers: All function handlers take two integers and return an integer. Handler 100 would calculate the product.
When preparing the map, ...
1
vote
2
answers
215
views
How to set int array pointer within for loop in c
The following code is trying to set the test array in the first for loop, but it can't be used in the second for loop.
int main()
{
int *test[3];
/** Try to set the array value one by ...
3
votes
1
answer
136
views
How do I cast a *mut T to a *mut [T]?
In Rust, both references and pointers to unsized types have metadata indicating the actual type of the reference. For example, a *mut [T] consist of a pointer to the start of a slice, plus a length ...
7
votes
6
answers
2k
views
C program: Use an array outside the scope it was defined in
I have some code in which an array of strings is defined in a conditional statement. The array is out of scope where I need it. So I defined another pointer in the outer scope. In the conditional ...
2
votes
0
answers
88
views
How to properly allocate dynamic memory for matrix operations in C [duplicate]
I am trying to learn C, and I want to specifically work with arrays and matrices as I do scientific simulations (coming from python!!). After writing few basic 1-D array codes in C, I am going for ...
2
votes
2
answers
129
views
Pointers, referencing, and dereferencing static strings in assembly language
I'm writing a little toy program to try to help myself better understand this language (AT&T syntax, x86_64 assembly language). Consider this code, if you'll be so kind:
.section .data
mystring: ....
2
votes
4
answers
239
views
Two pointers referencing the same memory location, possible to make null if we deallocate the space?
If two pointers are referencing the same memory location. Will it be possible to make one pointer null, if we deallocate that memory location?
For example:
#include <iostream>
using namespace ...
1
vote
1
answer
274
views
Using an asterisk as prefix or suffix for working with pointers
During a job interview, I was asked a question about the differences between **a, *a, a, a* and a** (which I failed).
I just asked ChatGPT about the difference between *a and a* and it came up with ...
4
votes
2
answers
225
views
How to free the value inside struct in c
I don't know how to reset the value field inside the Hello struct. It's a pointer pointed to an outside passed input argument.
typedef struct Hello {
void *value;
} Hello;
Hello* create_hello() {
...
-2
votes
3
answers
220
views
Can I declare a variable along with a pointer?
Can I declare a variable along with a pointer?
//like this
struct node n1,n2,n3,*start;
//or do i have to do it separately
struct node *start;struct node n1,n2,n3;
to declare variable alongside ...
4
votes
1
answer
140
views
Why don’t pointers appear in Python Tutor’s memory visualization in C?
I’m new to C and I’m trying to understand how pointers work. In this piece of code, when I run it on Python Tutor (pythontutor.com) to see how the stack and heap work, I never see the pointer being ...
5
votes
3
answers
335
views
The C 'Array-to-Pointer Decay' Paradox: Why do these function declarations behave identically? void func(char a[10]) vs void func(char *a)
I'm struggling to understand a core concept in C regarding Array-to-Pointer Decay when arrays are passed as function parameters.
It is well-known that when an array is passed to a function, it "...
0
votes
0
answers
141
views
Does accessing the contents of the string after calling reserve causes UB? [duplicate]
From another thread I found that
indeed allocates enough storage to hold at least n elements, but it doesn't actually fill the container with any elements
If elements are already allocated why ...
6
votes
1
answer
170
views
Is pointer arithmetic on a pointer that points to a destroyed array element well-defined?
In Cppreference the rules for pointer arithmetic include:
If P points to the i-th element of an array object x with n elements, given the value of J as j, P is added or subtracted as follows:
– P + J ...
-1
votes
1
answer
173
views
How to release dynamic memory on the heap in called function C++
#include <iostream>
using namespace std;
int* apply_all(int* arr1, int size1, int* arr2, int size2){
int* on_the_heap = new int(size1 * size2);
int temp = 0;
for(int i {0}...
0
votes
6
answers
277
views
Pointer to an array in a struct in C
I'm working (in C) with a struct that contains arrays of strings. How do I point to one of those strings?
To make it a bit clearer, consider:
struct Books {
char title[MAX1][MAX2];
char author[MAX1][...
3
votes
2
answers
171
views
Accessing a struct member from what is not the same struct type
The code below looks crazy, because I am interested in finding out the limits of what’s possible, and it isn’t exactly what I’m doing in my real code. It compiles without warnings and works as ...
5
votes
1
answer
241
views
How do strict aliasing rules apply to pointers-to-pointers-to-characters (and functions like `strtol`)?
How do strict aliasing rules apply to pointers-to-pointers-to-characters? For example, does the following contain undefined behavior? (godbolt)
#include <iostream>
#include <cstdlib>
long ...
2
votes
3
answers
199
views
What is the role of restrict here?
size_t hash(char const[restrict static 32]) [[reproducible]];
This is a function definition from Modern C by Jens Gustedt.
I understand that this is a more preferred alternate notation to a 32 char ...
-2
votes
1
answer
119
views
Array passed as an argument does not seem to be changing [closed]
I was tasked to write up a C program to sort an array using quicksort, without using recursion.
Original array:
-25, 87, 12, -6, 91, 3, -48, 70, 19, -33, 55, 2, -18, 99, 41, -72, 63, 15, -90, 27, 8, -...
3
votes
1
answer
95
views
Casting pointer-to-intptr_t to pointer-to-pointer
A pointer can be safely cast to intptr_t (or uintptr_t) and back (on platforms where those types exist), but what about casting a pointer-to-intptr_t into pointer-to-pointer and using that to modify ...
-2
votes
1
answer
107
views
Avoid mixing receiver types in generic constructor
Can the same -- object construction -- be achieved without mixing pointer and value receivers as per official docs ? https://go.dev/tour/methods/8 The problem is Error() cannot be just made with ...
2
votes
1
answer
207
views
Is difference between two pointers pointing to the same deallocated array well-defined in C++?
int main() {
const int length = 10000;
double *A = new double[length];
double *first = A;
double *last = A + length - 1;
delete[] A;
ptrdiff_t diff = last - first;
}
In C++, ...
22
votes
1
answer
2k
views
Is difference between two pointers pointing to the same deallocated array well-defined in C?
#include <stddef.h>
#include <stdlib.h>
int main(void)
{
const size_t length = 10000;
double* a = malloc(length * sizeof *a);
double* first = a;
double* last = a + length-1;
...
2
votes
3
answers
197
views
Is there a performance drawback when declaring 2D arrays using int** compared to int (*)[N] in C?
I have a question about the performance tradeoffs between different ways of storing 2D arrays in memory in C.
I know that if I declare a 2D matrix A with dimensions MxN by the following:
int (*A)[N] = ...
4
votes
3
answers
173
views
Passing a custom data type as a void pointer to a function
void do_something(void *data)
{
t_my_type *mt;
mt = (t_my_type *)data;
//mt->my_var = ...
//...
}
void do_something2(t_my_type *mt)
{
//mt->my_var = ...
//.....
10
votes
3
answers
621
views
Better way to search for a node in binary tree
This is the code I have written for searching a node in a tree as a part of my assignment:
typedef struct NODE
{
int key;
struct NODE *left, *right;
} Node;
Node *search(Node *head, int key)...
1
vote
1
answer
173
views
std::launder reachability precondition with data (void) pointers
I'm trying to wrap my head around the reachability precondition of std::launder in the context of (abstract) c++ pointer model. Here's a code snippet that makes me confused as to whether this ...
4
votes
2
answers
139
views
Pass C struct as "deep" const
I have a struct which holds some pointers to data it does not own, e.g.:
struct s {
int* x;
int* y;
};
I can then pass it as a const pointer itself:
int foo(const struct s* s) {
return *s-...
9
votes
1
answer
236
views
std::launder when there are two objects in the same memory location
I was doing some reading on std::launder, and I thought of a scenario that the standard didn't seem to address.
cppreference.com defines std::launder(T *p) like this:
Formally, given
the pointer p ...
6
votes
2
answers
265
views
How do I calculate the end address of a C struct in memory?
I have the following structure in my .c file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student {
char* name;
int age;
int id;
} Student;
...
3
votes
2
answers
159
views
Understanding static/dynamic array access with pointer arithmetic in C
I'm trying to understand how pointer arithmetic works in C.
Say if I have two arrays, one static and the other dynamic like so,
int a[10];
int * b = malloc(sizeof(int) * 10);
And lets assume each ...
2
votes
2
answers
196
views
Is it safe to .pop_back() from an std::vector in order to avoid pointers/memory shifting?
I have this class:
class Socket
{
[...]
pollfd* fdPtr;
};
And I have a Manager class that creates the actual pollfd objects and adds them to a std::vector named pollFdsVec, to then poll on ...
1
vote
3
answers
88
views
How do I update an address with a constant minus an address in a circular buffer
I have pointer into a delay line that I wish to update.
If the pointer (p) goes past the end of the buffer, I wish to wrap around to the start plus some value.
_Complex float buffer[BUF_LEN];
...
3
votes
1
answer
168
views
Use pointer and call function in C++
There are two classes A and B, each having functions f and g (with the same signatures).
The function bool is_A(uintptr_t ptr) returns true if and only if ptr points to an instance of A, and ...
1
vote
1
answer
79
views
Level of type casting of pointers?
I have an array of pointers to structs in C as
typedef struct{
int elem1;
char *elem2;
...
}example_t;
example_t *array[MAX_SIZE];
I did generic functions for add or delete pointers to ...
0
votes
0
answers
59
views
How is the rvalue_from_python_stage1_data convertible pointer is deallocated in boost python
Question
Can you provide some insight what is the role of the rvalue_from_python_stage1_data convertible pointer and how is being deallocated (memory managed) in boost python?
Background
According to ...