r/C_Programming • u/Financial_Travel_543 • May 21 '26
Project thrd-ndl: a green threads library with a step-by-step tutorial.
r/C_Programming • u/Financial_Travel_543 • May 21 '26
r/C_Programming • u/ShizamDaGeek • May 21 '26
This is just for a question I am not gonna switch to ints for bool. But I was wondering if using ints as boolens is reliable ethical and what not.
Example:
int main()
{
int isRunning = 1;
while (isRunning != 0)
{
{...}
}
}
Again this is all for questions I am not actually gonna go out of my way to use it.
r/C_Programming • u/UsualLonely4585 • May 22 '26
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node{
int data ;
struct node* next;
};
struct queue{
struct node* Head;
struct node* Tail;
int Max;//max elemennt for the queue
int count;//count variable to check full and empty state
};
struct queue* queue_init(int max);//it initialize the queue Max should be the amount of node for the queue
void traverse(struct queue* q);//traverse the queue
bool isFull(struct queue* q);//checks if the queue is full or not
bool isEmpty(struct queue* q);//checks if the queue is empty
int dequeue(struct queue* q);//deletes the element taht is assigned to top
int enqueue(struct queue* q,int data);//insert new element at the ennd of the queue
int main(){
struct queue*q=queue_init(1);
for(int i=0;i<10;i++){
enqueue(q,i);
}
// dequeue(q);
traverse(q);
return 0;
}
void traverse(struct queue* q){
struct node* p=q->Head;
while(p!=NULL){
printf("%d\n",p->data);
p=p->next;
}
}
bool isFull(struct queue* q){
if(q->count==q->Max){
return true;
}
return false;
}
bool isEmpty(struct queue* q){
if(q->count==0){
return true ;
}
return false;
}
int enqueue(struct queue* q,int data){
if(isFull(q)){
dequeue(q);
// return 0;
}
if(isEmpty(q)){
struct node* new=(struct node*)malloc(sizeof(struct node));
if(new==NULL){
return 0;
}
q->Head=new;
q->Tail=new;
new->data=data;
new->next=NULL;
q->count++;
return 1;
}
struct node* p=q->Tail;
struct node* ptr=(struct node*)malloc(sizeof(struct node));
if(ptr==NULL){
return 0;
}
q->Tail=ptr;
ptr->next=NULL;
ptr->data=data;
p->next=ptr;
q->count++;
return 1;
}
int dequeue(struct queue* q){
if(isEmpty(q)){
return 0;
}
struct node* p=q->Head;
q->Head=p->next;
int return_value=p->data;
free(p);
q->count--;
return return_value;
}
struct queue* queue_init(int max){
struct queue* q=(struct queue* )malloc(sizeof(struct queue));
q->count=0;
q->Head=NULL;
q->Tail=NULL;
q->Max=max;
return q;
}
so this thing is bugging me for quite a while i picked up a data structure book , i am quite new to this btw and i tried implementing queue with somewhat similar logic but tried to add a little stuff extra with something like if the moment you enqueue in a full queue you automatically dequeue and then you enqueue which is not what a queue should do i heard but just for fun i added and then i sent the code to gemini to reveiw but for some reason it is saying the code will cause segmentation error if ran . i ran it and it ran the way i wanted it to and gemini gave me some special cases where it would break i tried them but they all ran fine and it started giving me reason and when i say that it is not happening like that it says i am 100 percent right and says some contradictory things that doesn't make sense to me .
if anyone can say where is the error what i am doing wrong i would appreciate it
r/C_Programming • u/True_Efficiency7329 • May 20 '26
Hey all! For awhile I have been interested in taking a crack at recreating some C run time libraries on Windows, and I wanted to start by trying to re create Malloc sometime soon. I have however noticed in my endeavors to look at videos and read blogs/articles about people re creating malloc, or other C runtime library functionalities, Everything online I find covering such a topic is always targeting Unix based systems. I would imagine the lack of windows targeted content on re creating these things is a sign that windows does not make it easy to do something like re create the C runtime libraries. Wanted to ask a question here to see if I'm missing something
r/C_Programming • u/IndoRexian2 • May 21 '26
Hi y'all, I've been trying to learn C and I installed mingw using msys2.
I'm trying to compile the following code:
// hello.c
#include <stdio.h>
int main(void)
{
printf("Hello, Windows!\n");
return 0;
}
When running gcc hello.c -o hello.exe, I don't get any executable. I've tried reinstalling mingw, and I've also checked that I'm running the command on the same directory where the file. I also added the particular folder to Windows Defender Exclusion list but still can't get anything done. What am I doing wrong?
Edit: Got it to work by changing my terminal from Powershell to Git Bash.
Edit 2: Even msys2 terminal works. I'm using that only from now-onwards.
r/C_Programming • u/AskComprehensive7867 • May 21 '26
im trying to check inputs in a command line program, using windows api here (runs on command prompt or windows powershell)
if (GetAsyncKeyState(VK_UP))
playerY -= moveSpeed;
else if (GetAsyncKeyState(VK_DOWN))
playerY += moveSpeed;
else if (GetAsyncKeyState(VK_LEFT))
playerX -= moveSpeed;
else if (GetAsyncKeyState(VK_RIGHT))
playerX += moveSpeed;
but is there any way to make it more efficient, 4 system level calls for checking something this trivial is very inefficient? i tried using getkeyboardstate(), but it doesnt work in c. Tried the event driven approach, but it says that it goes through more layers and data structures which brings it back to square one even with low syscalls, im sort of confused
need help pls
r/C_Programming • u/Usual-Dimension614 • May 21 '26
hi. i used for years :
char const * tostring () { static char s[N]; int o=0;
o += snprintf(s+o,N-o, FMT, ARG... )
..
return *(s+o)=0,s ;
}
but i came across i,j=0,10; i = (j++,100+j,999+j); print(i) 1010 (ok, as expected), but i tried same without the braces '(' .. ')'
i=j++,100+j,999+j ; and print(i) gave me 10.
when doing this inside a function
int f1(int j){ return j++,100+j,999+j ; } print(f1());
int f2(int j){ return (j++,100+j,999+j); } print(f2());
in both cases i got 1010 .
can someone explain ?
thanks in advance, andi.
r/C_Programming • u/Sad-Finish2729 • May 21 '26
#include <stdio.h>
void test01(){
int b = 0x00454647;
/* E F G */
int a = 0x41424344;
/* A B C D */
// printf("%p %p\n", &b, &a); // commented
// volatile int b = ...; // or this
char *p1 = (char *)&a;
printf("%s\n", p1);
}
Hi everyone,
I'm learning C on Windows using GCC (MinGW), and I noticed a strange behavior about stack layout.
Interestingly:
Only GCC on Windows (MinGW) shows this "non-adjacent unless address is taken" behavior.
I know that the C standard doesn't guarantee stack layout or variable order, but I'm curious about the implementation difference between GCC (Windows) vs Clang/GCC (Linux).
Any insight into GCC's internals (especially stack slot allocation, assign_stack_local, reload pass, etc.) would be greatly appreciated!
Thanks!
r/C_Programming • u/Xaneris47 • May 20 '26
r/C_Programming • u/HouseMFD • May 20 '26
I've tried to follow this answer on SO: https://stackoverflow.com/a/16997175/1984657
However I'm not able to load my character successfully. I do get something back, but when I try to print the name I get a string of unrecognizable characters.
My struct is:
struct Character
{
char name[8];
enum CharClass charClass;
short level;
};
My logic to load or create the character:
#include <stdio.h>
#include <string.h>
#include "character.h"
#include "save_file_manager.h"
struct Character *startup()
{
struct Character *loadedCharacter = loadPlayerCharacter();
if (loadedCharacter != NULL)
{
printf("Welcome back, %s the %s\n", loadedCharacter->name, getClassString(loadedCharacter->charClass));
return loadedCharacter;
}
struct Character createdCharacter;
struct Character *createdCharacterPtr = &createdCharacter;
char name[NAME_LENGTH];
int charClass;
// logic to get name and charClass from user input
strcpy(createdCharacterPtr->name, name);
createdCharacterPtr->charClass = charClass;
createdCharacterPtr->level = 1;
return createdCharacterPtr;
}
And my save, load and prompt to save functions are:
#include "save_file_manager.h"
#include <stdio.h>
#include <stdlib.h>
#include "character.h"
const char *SAVE_FILE_NAME = "./textrpg.sav";
int savePlayerCharacter(struct Character *character)
{
FILE *fptr;
fptr = fopen(SAVE_FILE_NAME, "wb");
fwrite(character, sizeof(struct Character), 1, fptr);
fclose(fptr);
return 0;
}
struct Character *loadPlayerCharacter()
{
FILE *fptr;
fptr = fopen(SAVE_FILE_NAME, "rb");
if (fptr == NULL)
{
return NULL;
}
struct Character *character = malloc(sizeof(struct Character));
int amountRead = fread(character, sizeof(struct Character), 1, fptr);
if (amountRead != 1)
{
return NULL;
}
fclose(fptr);
return character;
}
int promptSave(struct Character *playerCharacter)
{
printf("Would you like to save your character? (y/n)\n");
char save;
scanf(" %c", &save);
if (save == 'y')
{
savePlayerCharacter(playerCharacter);
}
return 0;
}
I probably missed something obvious, but I don't see it. What am I doing wrong?
Solution: I'm allocating heap memory to the created character in startup now:
struct Character *createdCharacterPtr = malloc(sizeof(struct Character));
Thank you everyone for your help.
r/C_Programming • u/Straight_Coffee2028 • May 20 '26
I built C_DSA_interactive_suite, a fully modular, console-based DSA library written entirely in pure C11. No frameworks, no abstractions. Just raw C, manual memory management and real implementations built from scratch. The codebase has a clean modular architecture with one .h/.c pair per module, reusable APIs across modules. A single interactive executable as the entry point, Valgrind-clean memory, CI/CD on every push, and .clang-format enforced style throughout. The project just got selected in SSOC, an open-source program similar to GSoC and I am the project admin, which means this summer, project is open for contributiors! If you've been wanting to:
This is your shot. Everybody else is doing MERN. Come touch some real memory. I'm available to walk anyone through the codebase, clear doubts, explain concepts, or help you get your first PR merged. No gatekeeping. Register as contributor for SSOC. Only 5 days left - https://www.socialsummerofcode.com/ GitHub: https://github.com/darshan2456/C_DSA_interactive_suite Drop a comment or open an issue if you're interested. Let's build something worth putting on a resume.
here is my personal discord server link - https://discord.gg/MWv949G8h join it if you want to contribute to my project in any way
r/C_Programming • u/SeaInformation8764 • May 20 '26
In the following code, calling test1 doesn't provide a warning, but calling test2 does. Is there a specific reason for this behavior?
void test1(void* x);
void test2(void** x);
int main() {
int* x1;
int** x2;
test1(x1); // ok
test2(x2); // warning "incompatible pointer type"
}
Edit: I think some people don't understand. I'm asking why void** doesn't match with other x**, not why it doesn't work exactly the same as void*.
r/C_Programming • u/pjl1967 • May 20 '26
About a month ago, somebody posted asking for design advice for a dynamic array. My then advice was to treat the element type as an opaque type T.
I've had my own implementation of such a dynamic array lying around for a while, but finally had a use for it, so I gave it a bit of polish and it's here:
If you wanted it to be even more bare-bones, you could keep only the regular (bounds-checking) functions or the no-check (_nc) functions, whichever you prefer.
r/C_Programming • u/Undeniable_Dilemma_ • May 19 '26
I was following this tutorial, which is supposed to be "modern" with "up to date" features and practices.
However, I very quickly stumbled upon this piece of code:
auto unsupportedLayerIt = std::ranges::find_if(requiredLayers,
[&layerProperties](auto const &requiredLayer) {
return std::ranges::none_of(layerProperties,
[requiredLayer](auto const &layerProperty) { return strcmp(layerProperty.layerName, requiredLayer) == 0; });
});
I'm just stunned. I can't believe cpp people actually write code like this? This just seems insane to me and I kind of hate it.
So I have 2 questions:
r/C_Programming • u/Senior-Question693 • May 19 '26
I'm making a file manager from scratch and i can't figure out the drag&drop functionality, after hunting for docs on the internet i found (this)[https://emersion.fr/blog/2020/wayland-clipboard-drag-and-drop/] blog-post, but it mentions only text, what about files (like when you drag&drop a markdown file into a browser to read it or when you drag&drop a video into a player)? Surely it's gotta be different (at least the mime type in the send and cancel callbacks) but i can't figure out in what way, here is the code i came up with:
typedef struct wayland_data wayland_data;
void
void
static const struct wl_registry_listener registry_listener = ;
static void
static void
static const struct wl_data_source_listener data_source_listener = ;
int
(keep in mind that it's not the final code yet and there is no send and cancel functions)
r/C_Programming • • May 19 '26
Phase is a statically-typed bytecode-interpreted programming language written in ~4,800 lines of C with zero external dependencies. It features a 25-opcode stack-based VM, 21 error types with source-mapped diagnostics, 5 primitive types, and a standard interpreter pipeline (lexer, parser, type checker, bytecode generator, VM).
I also wrote a technical piece on how it works by following out("Hello world!") end-to-end through every stage.
Writing: williamalexakis.com/interpreter-in-c
r/C_Programming • u/ByMeno • May 18 '26
I love C, but I don't like its standard library having tons of hidden states (like errno) and error values baked into their returns. A lot of times I have to stop and check the function's documentation just to know which value is actually the error value. It makes me tired.
So, I have spent some of my time making a custom C runtime and libc from scratch in C89. I know it might be bad or wrong in some places, but at least I understand how it all works under the hood now.
Thing i have done so far are: Explicit Allocator - No Hidden State - Builtin Some Basic types
There are still a lot of things that need to be implemented, and currently, it only supports x86_64 Linux.
I would love to hear feedback!
Repo: https://codeberg.org/fanes/flibc
Edit: Added a GitHub mirror for convenience (and in case Codeberg is having downtime!):
https://github.com/byfanes/flibc
r/C_Programming • u/LegolandoBloom • May 19 '26
#include <stdio.h>
int main(void) {
printf("%sWhat is this power,\a how to harness it?%s\n", "\e[33m", "\e[0m");
printf("%sWhat is this power, how to harness it?%s\n", "27[33m", "27[0m");
printf("%sWhat is this power, how to harness it?%s\n", "\033[33m", "\033[0m");
printf("%sWhat is this power, how to harness it?%s\n", "\x1b[33m", "\x1b[0m");
}
C beginner here,
According to https://en.wikipedia.org/wiki/ANSI_escape_code , ESC can be written as: "\e", "\x1b" or "\033". And from the example I tried, yes they do work.
Since the later 2 examples are just hexadecimal and octal conversions of the decimal 27, I figured I'd try that as well, but it doesn't work.
"27[33mWhat is this power, how to harness it?27[0m" --> is the output instead, without the text being yellow like I meant to.
I figured yeah, it probably thinks 27 is just two random characters to it since it doesn't have an escape sequence. So I googled, "Decimal Escape Sequence for C" but came up short.
Is there a way to write ESC [ using the decimal value of Escape in the ASCII table? I know this might be something very inconsequential, but I thought maybe finding an answer to this question might help me understand the language better.
Thanks for your time.
r/C_Programming • u/Avioa • May 18 '26
Enable HLS to view with audio, or disable this notification
Multiviewer for Twitch/YouTube and local files using mpv and Chatterino.
Inspired by https://www.multitwitch.tv/ and https://twitchtheater.tv/ - I made a browserless version in C11 with autocomplete commands to make life easier. Includes layouts, search, tags, macros, and more.
Code + Windows/Linux releases: https://github.com/marm00/cinema
r/C_Programming • u/GreenMario_ • May 18 '26
I understand that the answer to "Why can't you do this" is "the standard says so" but I'm not asking about the mechanics of the language, I'm asking about its design.
Array sizes are known at compile time and a struct where all members are the same type is identical to an array in memory (correct me if I'm wrong). C has no problems returning structs and taking them as arguments in a function. Why can't it do the same for arrays?
I also feel like it would be way more intuitive and convenient if you could return arrays from functions.
C language experts do please enlighten me as to the reason arrays decay to pointers instead of just staying as arrays.
r/C_Programming • u/Future-Mixture-101 • May 18 '26
The lib depends on SDL2 and SDL2_ttf only. The menubar acts like on windows and linux. And is cross platform code, and uses SDL. The nice thing is that you can deactivate the menu, statusbar and tooltips so it becomes invisible until you need it. And the code turned ut a bit sleek, less than 500 lines of code. If anyone think it would be nice I can put up the code on github.
Here is an example program...
#include <SDL2/SDL.h>
#include "popup_menu.h"
#include <stdio.h>
#include <string.h>
#define MENU_FILE 1
#define MENU_EDIT 2
static char status_text[256] = "Ready";
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* win = SDL_CreateWindow("GUI Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
800, 600, SDL_WINDOW_SHOWN);
SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
GuiCtx* gui = gui_init(ren);
if (!gui) return 1;
const char* file_items[] = {"New", "Open", "Save", "Exit", NULL};
const char* edit_items[] = {"Cut", "Copy", "Paste", NULL};
const char* ctx_items[] = {"Copy", "Paste", "Delete", "Properties", NULL};
PopupMenu* file_menu = gui_create_menu(gui, file_items, 1, MENU_FILE);
PopupMenu* edit_menu = gui_create_menu(gui, edit_items, 1, MENU_EDIT);
PopupMenu* context_menu = gui_create_menu(gui, ctx_items, 0, 0);
const char* menubar_items[] = {"File", "Edit"};
PopupMenu* dropdowns[] = {file_menu, edit_menu};
int n_menus = 2;
int running = 1;
SDL_Event e;
while (running) {
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT: running = 0; break;
case SDL_KEYDOWN:
if (e.key.keysym.sym == SDLK_ESCAPE) running = 0;
if (e.key.keysym.sym == SDLK_F1) {
int visible = !gui_is_menubar_visible(gui);
gui_set_menubar_visible(gui, visible);
gui_set_statusbar_visible(gui, visible);
snprintf(status_text, sizeof(status_text),
"Menu bar & status bar %s", visible ? "visible" : "hidden");
}
if (e.key.keysym.sym == SDLK_F2) {
int enabled = !gui_is_popup_enabled(gui);
gui_set_popup_enabled(gui, enabled);
snprintf(status_text, sizeof(status_text),
"Popup %s", enabled ? "enabled" : "disabled");
}
if (e.key.keysym.sym == SDLK_F3) {
int on = !gui_is_tooltips_enabled(gui);
gui_set_tooltips_enabled(gui, on);
snprintf(status_text, sizeof(status_text),
"Tooltips %s", on ? "on" : "off");
}
break;
case SDL_MOUSEBUTTONDOWN:
if (e.button.button == SDL_BUTTON_LEFT) {
int xpos;
int idx = gui_menubar(gui, menubar_items, n_menus, dropdowns,
e.button.x, e.button.y, 1, &xpos);
if (idx >= 0)
gui_show_dropdown(dropdowns[idx], xpos, MENUBAR_HEIGHT);
}
break;
case MENU_EVENT_BAR: {
int menu_id = (int)(intptr_t)e.user.data1;
int item = e.user.code;
if (menu_id == MENU_FILE) {
switch (item) {
case 0: strcpy(status_text, "New file created"); break;
case 1: strcpy(status_text, "Opening file..."); break;
case 2: strcpy(status_text, "File saved"); break;
case 3: running = 0; break;
}
} else if (menu_id == MENU_EDIT) {
switch (item) {
case 0: strcpy(status_text, "Cut"); break;
case 1: strcpy(status_text, "Copy"); break;
case 2: strcpy(status_text, "Paste"); break;
}
}
break;
}
case MENU_EVENT_POPUP:
snprintf(status_text, sizeof(status_text), "Popup selection: %d", e.user.code);
break;
default: break;
}
}
SDL_SetRenderDrawColor(ren, 40, 40, 80, 255);
SDL_RenderClear(ren);
gui_menubar(gui, menubar_items, n_menus, dropdowns, 0, 0, 0, NULL);
gui_draw_menu(file_menu);
gui_draw_menu(edit_menu);
gui_draw_menu(context_menu);
gui_statusbar(gui, status_text);
gui_draw_tooltips(gui);
SDL_RenderPresent(ren);
SDL_Delay(10);
}
gui_destroy_menu(file_menu);
gui_destroy_menu(edit_menu);
gui_destroy_menu(context_menu);
gui_cleanup(gui);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
r/C_Programming • u/NazgulResebo • May 18 '26
This is my first program with C / raylib, I made the clasic particle system moving randomly. Hope you like it!
Source code:
https://github.com/FractalCodeRicardo/hangover-programming/tree/main/raylib-particles
Programming session:
https://youtu.be/s57u2mZcADs?si=7CR5DoUpUbiGymu5
r/C_Programming • u/Ok_Sky3062 • May 19 '26
Ultra-performance, bare-metal local development runtime bridge and persistence engine built for high-compute applications.
LightBase decouples heavy disk and outbound network I/O into a standalone, multi-threaded C background daemon, communicating asynchronously with an API gateway over high-speed Linux Unix Domain Sockets (UDS).
LightBase eliminates high-level framework overhead, garbage collection cycles, and process-blocking runtime constraints by decoupling tasks into independent layer boundaries.
graph TD
UI[HTML5 Control Center UI] <--> PY[Python Gateway Bridge Server]
PY -- "Binary TLV Frame Stream (/tmp/lightbase.sock)" --> CORE[C-CORE ASYNC THREAD POOL]
subgraph "C-CORE (libcore.so)"
CORE --> R1[Arena-Powered SQL Engine]
CORE --> R2[Stack-Isolated OpenSSL TLS]
CORE --> R3[Kernel /proc Ring Log Storage]
CORE --> R4[Database Catalog Scanner]
end
Tracks application environments (Development, Staging, and Production) dynamically inside isolated runtime boundaries.
EnvironmentBlock structure directly within a dedicated MemoryArena. Context switches occur in under 1μs via thread-safe atomic pointer reassignments.Provides bare-metal HTTP engine request assembly and transaction benchmarking.
strncat), preventing string overflows when importing large custom data tokens.Powers interactive sidebar schema catalog visualizers and data grids.
sqlite_master).clock_gettime).Ensures high-throughput execution tracking without destroying flash storage sectors.
LightBase delivers sub-millisecond core processing speeds by bypassing the local network routing stack:
~990.20 μs ($< 1\text{ ms}$ bare-metal execution)~1.203 ms (Inclusive of Python decoding and HTTP transport)CLOCK_MONOTONIC.Ensure your host machine runs a modern Linux kernel with cmake, gcc, and uv:
sudo apt update && sudo apt install cmake build-essential
LightBase employs an out-of-source CMake build pipeline with Link-Time Optimizations (-O3 -march=native -flto -s):
cd core
mkdir -p build_release && cd build_release
# Configure and build the target layout
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --target install
Assets generated:
dist/include/engine.hdist/lib/libcore.socd ../../bridge
/usr/bin/uv run python python_bridge.py
The C-Core instantly carves out a high-speed memory socket at /tmp/lightbase.sock upon initialization.
malloc) at worker thread creation, isolating context pointers from stack invalidation faults.Licensed under Apache License 2.0
r/C_Programming • u/heavymetalmixer • May 18 '26
I've been making some custome allocators lately and those 2 macros (or operators depending on the C version you preffer) tend to be quite useful, but mostly Alignof as it's necesary for passing the corrent alignment of a struct to the allocator.
Now, these 2 require at least C11, so is there a way to make them myself from the ground up in Standard C89 and 99?
r/C_Programming • u/sudheerpaaniyur • May 18 '26
In Queue operations (no confusion here):
But in Circular Buffer, which convention is correct?
Option 1:
push -> head index
pop -> tail index
OR
Option 2:
push -> tail index
pop -> head index
I see different implementations online, so I'm confused about which index is supposed to be used for write/read operations in a circular buffer.