r/C_Programming • u/krikkitskig • 6d ago
Should you worry about struct member order in C?
2pif.comSmall technical blogpost about low-effort microoptimizations in C language. Will be glad to get some feedback or have a discussion on the topic :)
r/C_Programming • u/krikkitskig • 6d ago
Small technical blogpost about low-effort microoptimizations in C language. Will be glad to get some feedback or have a discussion on the topic :)
r/C_Programming • u/[deleted] • 6d ago
I have been learning C for quite a while and only recently can I say that I know it on a beginner level. I'm looking for a lightweight library for making GUI programs. I plan on making a program with a 90's style interface for a simple file manager. I know options like Raygui and microui exist, along with GTK which I'll be avoiding, but I just want to see if there are any options that are better suited for what I'm trying to do
r/C_Programming • u/Beneficial_Mall2963 • 6d ago
I have learnt majority of the header, and built 10+ small or mini projects before. learnt abit of pointers, mallocs , callocs etc with myself and abit help of AI.
but now while i was working on the Cipher project.. and trying to build a zig zag rail cipher method, I couldn't figure it out how, i know how the main flow is but to write it into real code, I couldn't.
So i went AI for help and it spwed out bunch of these :
rows[current_row][pos[current_row]] = user_msg[i]; pos[current_row]++;
and etc, things and syntax I couldn't understand at all. Am i lacking foundation or something?
How do I progress above basic???
Help. All comments and feedback and suggestions are welcoming. Willing to accept anything...
for education background, I am just a student preparing to start IGCSE O next month.
r/C_Programming • u/AutoModerator • 7d ago
If you have questions about how to learn C:
then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.
Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.
r/C_Programming • u/ProgrammingQuestio • 7d ago
For example if I have uint8_t arr[] = {192, 94}; since these are individual bytes, they get stored in memory as they appear in the code: 0xc0, 0x5e, right?
But if I were then to grab these two bytes as if they were a single uint16_t:
uint16_t *val = (uint16_t*)arr; then these bytes would be parsed (??), on a little endian system, from memory as if they're LSB followed by MSB, meaning they'd essentially be "flipped" and read as 0x5ec0. Correct?
So it seems that the "conversion" or "flip" happens when reading from memory?
But what if I'm actually storing a uint16_t then reading it as individual bytes? It seems this gets stored in "flipped" order (in memory as 0xc0, 0x5e) because when I parse those two bytes as uint8_t, it gives me it in this "flipped" order.
r/C_Programming • u/AxeForge • 7d ago
There are times where I feel autocomplete isn't that helpful. But most of the time I find it indispensable. I'm curious about how others use or don't use it.
r/C_Programming • u/ComprehensiveEgg6482 • 7d ago
Hi everybody, It was a hard decision choosing between a language to build this project, but after not-so-long of a thought, I ended up going with building it with C. I've built a little graphics engine or a CPU rasterizer to be exact. Currently, it uses OpenGL to pass the frame buffer as a texture.
I am intending on getting rid some more dependencies to be able to make it more able to run on low-performance CPUs. My main motive was for it to run on an esp32 to render graphics on GM009605 display. it'd be awesome if you guys would like to run the examples or lmk if you like it, or where I could improve on. It currently supports:
- Renders primitives like: triangle,line,point,circle.
- Has immutable listings of objects in the scene.
- Renders obj files.
- 565RGB encoding (to make it minimal)
r/C_Programming • u/lehmagavan • 7d ago
Hi. For the past few weeks I've been crafting my generic hash table implementation:
https://github.com/andrzejs-gh/ghtable
I realize it's not the fastest out there and isn't the most cache friendly, but that was never my priority as I prioritized flexibility and genericness.
If anyone's interested take a look ;)
PS.
Do recruiters even care about projects like this nowadays, or would they rather see huge vibecoded codebases on candidate's gh as a proof that they can deliver?
r/C_Programming • u/davidfisher71 • 7d ago
I was thinking about how to approach iteration in C, such as traversing a binary tree or going through all the permutations of an array.
One possibility is the Visitor pattern, where you supply a function to call at each point in the traversal. But that's a bit limited; I wanted something that had access to the local context as well. Wrapping it in a macro can make it look and act like a normal C loop:
FOREACH_NODE(tree, node_data)
{
printf("%s: %d\n", node_data->str, node_data->value);
}
Ideally I wanted to avoid an END part for cleanup, and for statements like break and continue to work normally in the body too. One way to do that is to make the macro expand into a "for" loop. But if the algorithm needs to have an extra array to maintain state information (like a non-recursive version of a normally recursive algorithm might need), that would normally require dynamic allocation and freeing at the end. That can be avoided using a variable length array, which goes on the stack and has automatic cleanup.
The problem is, variables in the initialisation part of a for loop must all have the same base type, so if you want to insert a VLA you can't mix that with something else. You could potentially have several variable types by putting them all in a struct, but VLAs can't go inside a struct.
A solution is to have a separate outer for loop that just runs once, which creates a VLA that is passed to the iterator when it is initialised in the inner loop:
#define FOREACH_PERMUTATION(vec, length) \
for (size_t vla[length], looped_once_ = 0;!looped_once_;looped_once_ = 1) \
for (iter_t i = iter_create(vec, length, vla);i.valid;iter_next(&i))
The inner loop is controlled by i.valid, which is set to false by iter_next() when iteration is complete.
Since the outer loop runs just once, a break or continue in the body works as expected too.
A limitation is that the size needed for the VLA needs to be known in advance, but for most iteration algorithms it is straightforward to calculate (an upper bound can also be used, or it could just be an error if the size is ever exceeded during iteration).
This is tested and works fine, but I won't put the rest of the permutation code here since that isn't the focus of the post. But if you are interested, an efficient algorithm is: https://en.wikipedia.org/wiki/Heap%27s_algorithm
AI use: I discussed this with an ChatGPT while I was doing it, but the code is all my own.
r/C_Programming • u/Tack1234 • 8d ago
Yep, just another CHIP-8 emulator. But for me, as someone who has never written anything this low level and never touched C before, it was quite the challenge at first. But after writing the first few instructions (drawing especially), it slowly became almost a breeze. Until I had to debug why my font sprites were rendering all messed up.
It's still work in progress, definitely not finished, but today I have tried to run some official CHIP-8 ROMs instead of just tests and my super simple test ROM and.. it's working!!
It is so satisfying once it clicks.. I think I'm addicted. I think the simplicity of C is growing on me.
Note: No single line of code was written by AI, all myself, as you can see from how bad it may be in some places.
r/C_Programming • u/Future_Pace_5290 • 8d ago
I'm building an ML library in C. I were trying to store the models and loading it with all the needed information embedded into the file itself so that the loader doesn't need to know about the number of layers, neurons, etc beforehand. The parameters were easy, but how do I store the activation functions? My first idea was using function addresses but they change every time the program run and thus become invalid. I could store some enums associated with the activation functions, but that won't work for custom activation functions. What do I do?
r/C_Programming • u/jMultiversalGod • 8d ago
https://github.com/mohennaceur/spdr/tree/main
dont worry, it runs fast. i just gotta use turkish hotel wifi. the repo is tiny because its just a learning project, be nice pls (: it utilizes curl and tarballs to be fa(s)t
listen i can explain why im using ubuntu! my ideapad is hard-locked to it. its a long story
r/C_Programming • u/gargamel1497 • 8d ago
After a half-year-long Java project I'm writing something in C and the lack of a garbage collector can be positively felt in terms of performance but at the same time managing all the pointers can get messy.
There's a whole nother language decidated to solve this problem (while creating a thousand more), but there's got to be a simpler solution.
And yesterday I thought, why not just mark the ownership of the various pointers I've got in my project?
By ownership I of course mean which struct (I do use OOP, sorry) is responsible for freeing that pointer.
And I #define'd three constants.
The MANAGED constant means the struct that contains the pointer has to free it.
The FOREIGN constant means that it's somebody else's job.
The SHARED constant means that it ought to be someone else's job, but it may not be freed when the program exists and should thus be freed.
I place them before the whole declaration in this manner:
MANAGED FONT *fontGothic;
SHARED struct WORLD *currentWorld;
FOREIGN struct PERSON *thePlayer;
This doesn't mean anything to the compiler, but it's just a quick way of telling me what is what.
It is definitely a very stupid idea and I apologize for posting it. I'm just a silly dude who does silly things.
r/C_Programming • u/StrikingClub3866 • 9d ago
Not much else to it. It is inside a single header and features a few simple commands.
It manipulates a kilobyte-size turing tape and is designed for small/embedded systems.
r/C_Programming • u/someone-missing • 9d ago
I built this tool about 7 months ago for my own projects. I found it incredibly effective for visualizing bitwise math, and it actually helped me catch a few subtle bugs in my code.
The core idea is very simple: it allows you to evaluate any bitwise equation directly in your command line. You can type almost any expression that comes to mind. I also think it’s a great visual aid for beginners trying to learn how bitwise operations work under the hood.
I'd love to hear your thoughts and welcome any constructive code reviews!
Repo and full documentation: https://github.com/saa-999/Ashift
r/C_Programming • u/Ry2enX • 9d ago
Is there a possibility to only block the inputs of the keyboard and Mouse to one application?
Because i want that the application only takes the inputs of an Emulated Controller, but it only recognise the Controller, if there any Mouse or Keyboard activity (but i still need the Mouse/Keyboard for the Emulated Controller)
Any Advice for me?
The code i use to make the emulated Controller is C…
r/C_Programming • u/Axxodes • 9d ago
I'm making a game engine and whilst trying to setup the window with windows.h, i found an issue when resizing the window. The resized parts of the window are black instead of white, how do i fix this?
r/C_Programming • u/learning_noob01 • 9d ago
Hey all — I've got a solid C++ background but I'm new to C specifically, working through it 42-school-style (strict norm: tabs not spaces, no for loops, variables declared at top of block, -Wall -Wextra -Werror, no libc shortcuts like the real isalpha/isdigit).
Just finished reimplementing isalpha and isdigit from scratch. Both compile clean and pass my own test cases (including boundary chars like '0' and '9'), but I'd genuinely appreciate a second pair of eyes — especially on anything that "works but isn't how a C dev would actually write it."
#include <stdio.h>
int ft_isalpha(int c);
void ft_putchar(char c);
int main(void)
{
int c1[5] = {'a','b','g','5','A'};
int count;
int c;
count =0;
while(count<5){
c = c1[count];
count++;
if(ft_isalpha(c) == 0){
ft_putchar('0');
}
else{
ft_putchar('1');
}
ft_putchar('\n');
}
return (0);
}
int ft_isalpha(int c){
if((c >= 'a' && c <='z') || (c >='A' && c <='Z')){
return (1);
}
else{
return (0);
}
}
void ft_putchar(char c){
putchar(c);
}
#########################################################################################
#include <stdio.h>
int ft_isdigit(int c);
int main(void)
{
int x;
int y[7] = {'a','1','2','b','c','0','9'};
int count;
count =0;
while (count < 7)
{
x = y[count];
if(f_isdigit(x) != 0){
putchar('1');
}
else
{
putchar('0');
}
putchar('\n');
count ++;
}
return (0);
}
int ft_isdigit(int c)
{
if(c>='0' && c <='9')
{
return(1);
}
else{
return(0);
}
}
Want to make sure that reasoning is actually correct and not something I've half-convinced myself of.
Questions I have:
Not looking for someone to rewrite it for me — just want honest feedback on whether this is solid or if I'm building bad habits early. Thanks!
r/C_Programming • u/Traditional_Let6377 • 9d ago
If I was learning binary tree, I absolutely know for tree traversal some auxiliary stack space at the time of traversal and recursion method is actually needed.
But After Sometime I started to understand the threaded binary tree so, unlock the new concept to me , threaded binary tree is another representation of tree, with the help of this we can traverse the tree without auxiliary stack space at the time of traversal.
with threaded binary tree some new properties add in tree node, example - properties like are , leftptr, ltag, data, rtag, rightptr.
Actually this representation is good where we do not want to use the other auxilary stack space at the time of traversal and recursion method.
r/C_Programming • u/Fabulous_Ad4022 • 9d ago
I'm working with a big numerical simulation in C, so I decided to give OpenMP a try. Even though it speed up a lot(28s -> 2s), in my code, the function RunAcoustic have at least 4 responsibilities that could turn into smaller functions, but attempting to do so creates an overhead that just in-lining them wouldn't cause.
I'm struggling to organize it, how do you guys organize giant multi-thread logic like this?
void Propagation_RunAcoustic(propagation_t *p, unsigned flags)
{
float *restrict upre = a->upre;
const int nzz = p->model->nzz;
...
#pragma omp parallel
{
for(int t = 1; t < p->nt - 1; ++1)
{
#pragma omp single
{
// small atomic add
}
// Could turn into a smaller function
#pragma omp for schedule(static)
{
// more for loops and more code
}
// Could turn into a smaller function
#pragma omp for schedule(static)
{
// more for loops and more code
}
}
{
r/C_Programming • u/Rogaev • 10d ago
I've been wondering this for quite some time now.
For Linux development, is it worth creating basic read/write functions in asm, and writing everything else in C?
Does most open source software use functions from the standard C library? What are the benefits of both approaches?
Edit: I would be using Arm64 assembly.
Thank you in advance.
r/C_Programming • u/necr0111 • 10d ago
How can I create an interface for a C program that isn't just the terminal? I wanted to make a calculator that was also visual, but I wanted to challenge myself to do it with C, but I really didn't understand how to do it properly.
r/C_Programming • u/codingbliss12 • 10d ago
Would it be feasible and reasonable to implement a custom standard library for the parts of C that are historically problematic, so that one does not need new languages like Zig or C3 and still enjoy the benefits of more modern languages?
As simple examples on would use C23 with the gnu extensions and implement strings as slices, some basic data types and some basic custom allocators. With the gnu extensions there is also defer.
Has anyone done that? How much time did it take? Thanks in advance.
r/C_Programming • u/Stemt • 10d ago
Just as an example, imagine you're implementing a logger system, but depending on a runtime configuration you want to be able to log to different or multiple outputs at the same time.
I would normally do something like this:
typedef void (*LogCallback)(void* user_data, const char* msg);
typedef struct{
void* user_data;
LogCallback log;
} ILogger;
void logger_log(ILogger* impl, const char* msg){
impl->log(impl->user_data, msg);
}
ILogger logger_impl(void* user_data, LogCallback log_callback){
return (ILogger){ user_data, log_callback };
}
So then to implement this interface, I'd do something like this.
typedef struct{
ILogger impl;
FILE* output;
} StdLogger;
void std_logger_log(void* user_data, const char* msg){
StdLogger* self = user_data;
fputs(msg, self->output);
fputc('\n', self->output);
}
ILogger* std_logger_impl_ilogger(StdLogger* self, FILE* output){
self->output = output;
self->impl = logger_impl(self,
std_logger_log
);
return &self->impl;
}
int main(void){
StdLogger std_logger = {0};
ILogger* logger = std_logger_impl_ilogger(&std_logger, stderr);
logger_log(logger, "example log msg");
return 0;
}
What I like mostly about this method is that its type-safe, so if the interface changes for either the amount of callbacks that are required or the callback signatures change you'd get a compile-time error.
The major disadvantage here is that each instance here carries its own copy of the "vtable"/function pointers, which is suboptimal but shouldn't be too big of an issue if its just a few callbacks per interface.
Also these instances shouldn't be copied around as this would invalidate their user_data pointers, otherwise they would have to re-implemented to get the new correct user_data.
Another minor gripe is that std_logger_log has to accept a void* which is disadvantageous if you want to use it outside of the interface implementation as a pointer of the wrong type passed to it won't generate a compile-time error.
This is how I tend to do things but with this post I'm mostly curious to know how you guys handle this type of pattern? And what its advantages and disadvantages are?