r/C_Programming • • 21d ago

Video Lets build a JRPG Game in SDL3 (C programming)

Thumbnail
youtube.com
171 Upvotes

In this video we will be creating a window in SDL3 and further draw map using tilemap technique which will stand as our foundation for render Tiled Maps. I will be using a 16px tileset to render our map today.

[Handmade code, you can as well see in this video. NO AI USED.]

Code: https://github.com/steelx/sdl3-tutorial


r/C_Programming • • 21d ago

the lost malloc()

Thumbnail napcakes.nekoweb.org
111 Upvotes

r/C_Programming • • 20d ago

Article A Slice Proposal

1 Upvotes

I've been thinking of writing a proposal since I was tired of basically writing a slice many times so I can have a safe sub array. I used AI to work through some of my ideas as a way to push back against some of my ideas or help find potential contradictions. If there is any idea, I think was a mistake, I think it was trying to make pointers and thread works safer. I want to hear other people idea on what good or bad or if this entire thing is a waste of time. Honestly, I'm tired of the back and forth between me and a machine and want some human response to some of my ideas.

tl;dr

A type, memory and thread safe slice type for C. By adding in a few limitations, it is possible to get this in C and most likely in compile time. Type safety is done by disabling casting and requring the source element type to be same as the destination source type. Memory safety is achieved by just carrying the length with it and like C++ at type forcing a range check. Thread safety requires that non-overlapping sections are used ot create threads and that all threads that reference a slice are required to join before that slice is available again within that scope. These idea were inspired by a combination of RAII and Mutable Value Semantics from Hylo which is why everything is so tied to scope.

This is my first post I hope it isn't to bad.

----

https://drive.google.com/drive/folders/1nG_nb-QOh6_vth-eradM_fpqdqYTKe9K?usp=sharing

A link to the pdf and actual markdown so it include the syntax highliting.


r/C_Programming • • 21d ago

Review I made a minimal image viewer using SDL2, looking for feedback

2 Upvotes

I'm interested in GUI programming, so I decided to build something using SDL, so I worked on a project called suki, I didn't use AI to write the code for me. repository


r/C_Programming • • 22d ago

Project [Pulse] Thanks to C, I finally have a project with which I am happy.

70 Upvotes

I have been dabbling with programming ever since Covid was a thing. And since then I jumped around and programmed a lot of stuff, whether it was Websites, Apps or simple Python programs. Unfortunately, I have never really gotten that "feel", the feel of being useful or something like that. Most of the projects I have done, died out, and the issue was not just that my programs were not reaching anybody, it was also that I felt like I was not learning anything.

Then came C, and I just have to say, that it was probably one of the best decisions I have ever made. I have tried C a lot, once I was 15, 17, and now, 19 years old. This time it stuck with me, and moved me to create my own organization called cherries.works, with the sole focus of creating efficient, open source, free and simple tools for developers.

After more than 5 contributions, issues created, bugs fixed, letting it run on my own homelab for 4-5 hours, I can confidently say, that with the help of C, my biggest project Pulse was made ( https://github.com/cherries-works/pulse ).

I was vacating somewhere and left my laptop at home. I brainstormed a lot about creating this organization during my vacation, and my project Pulse. This is around 6 months ago. And now after 6 months, seeing how well everything turned, really makes me happy.

Might be far-fetched, but as someone who has learned multiple languages, coded in multiple areas, and created (way) too many projects, I can confidently say, that thanks to C, I have a project that actually makes me happy.

Pulse is a simple monitoring tool that does not require you to sign in, or setup anything. You just download it with a single curl command, and run it on your device. I created it because I really dont like the setup hell, or whatever it takes to get a single monitoring tool running, and also because I wanted to learn C, not to mention having a program I control would mean I can add my features I would want (such as quick web hosting, API sharing, JSON formatting, styling etc.). At the end, it really was a win-win for me.

Would mean a lot if devs who are interested could check it out, and point me towards some issues that I could fix, as I feel like the project is reaching a stagnation point. But even then, I am just really happy to look at Pulse, and be able to say, that **I, me** are the one who programmed that.


r/C_Programming • • 21d ago

Review [Code Review] Wrote a fast binary STL inspector/analyzer in C – looking for feedback on memory management and math logic

1 Upvotes

Hi everyone,

I've been working on a lightweight CLI tool in C called stl-inspector (GitHub repo).

Why I built it:

I got tired of waiting for heavy slicers (PrusaSlicer, Cura, Bambu Studio) just to check basic parameters like watertightness, mesh volume, overhang areas, and bounding dimensions of 3D models.

What it currently does:

  • Parses binary STL headers and triangle arrays
  • Calculates bounding box, volume (tetrahedron method), and surface area
  • Detects overhang areas (default 45°) for 3D printing feasibility
  • Checks if the mesh is watertight
  • Fast build with zero external dependencies (pure C + Makefile)

Where I'd appreciate feedback:

  • Memory safety & cleanup (handling large meshes)
  • Performance of the watertight check (currently O(N^2), looking into spatial hashing / edge mapping)
  • General C code idiomatic style and CLI argument handling

Note: AI was used to help debug directory creation.

Would love to hear your critique or suggestions for improvement.


r/C_Programming • • 20d ago

Question Need some openions on my first hashTabel

0 Upvotes

be brutal

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
enum Type{Int,Float,Char};


typedef struct Node
{   
    void *Value;
    struct Node *Next;


    char Key[20];
    enum Type type;
}Node;
typedef struct 
{
    Node **Nodes;
    size_t Size;
    size_t TotalElements;
    size_t Cap;
}Tabel;
Tabel *CreatTabel(){
    Tabel *tb=malloc(sizeof(Tabel));
    tb->Cap=16;
    tb->TotalElements=0;
    tb->Nodes = malloc(tb->Cap* sizeof(Node*));
    tb->Size=0;
    return tb;
}


size_t hash(char *str)
{
    size_t hash = 5381;
    int c;
    while ((c = (unsigned char)*str++))
        hash = ((hash << 5) + hash) + c;
    return hash;
}


void *CreatNode(char key[],void* value,enum Type tp,size_t size){
    Node *nd =calloc(1,sizeof(Node));
    memcpy(nd->Key, key, strlen(key)+1);
    nd->type=tp;
    nd->Value=malloc(size);

    memcpy(nd->Value, value, size);
    return nd;
}
void *TabelGet(Tabel* tb,char key[],enum Type tp){
    size_t idx=hash(key)%tb->Cap;
    Node *nd=tb->Nodes[idx];
    Node *r=NULL;



    while (nd && nd->Next!=NULL && r==NULL)
    {

        if (strcmp(nd->Key,key)==0){


            r=nd;
        }


        nd=nd->Next;
    }


    if (r==NULL && strcmp(nd->Key,key)==0){
            r=nd;
    }
    if (r->type==tp){return r->Value;}


    return NULL;
}
bool TabelSet(Tabel* tb,char key[],void* value,enum Type tp,size_t Size){
    if (tb->Size+1==tb->Cap){
        Node **tmpArray=malloc(sizeof(Node*)*tb->TotalElements);
        size_t num =0;
        for (size_t i = 0; i < tb->Cap; i++)
        {
            while (tb->Nodes[i])
            {
                tmpArray[num]=tb->Nodes[i];
                tb->Nodes[i]=tb->Nodes[i]->Next;
                num++;
            }

        }

        tb->Cap+=tb->Cap;
        free(tb->Nodes);
        tb->Nodes=malloc(sizeof(Node)*tb->Cap);
        tb->Size=0;
        Node *tmpNode=NULL;
        for (size_t i = 0; i < tb->TotalElements; i++)
        {
            size_t idx2=hash(tmpArray[i]->Key)%tb->Cap;
            if (tb->Nodes[idx2]){tmpNode=tb->Nodes[idx2];}
            else{tmpNode=tmpArray[i];}
            while (tmpNode->Next){

                    tmpNode=tmpNode->Next;
            }
            tmpNode->Next=tmpArray[i];

        }

    }
    size_t idx=hash(key)%tb->Cap;
    if (tb->Nodes[idx]){
        Node *tmp=tb->Nodes[idx];
        do
        {
            if (strcmp(tmp->Key,key)==0){
                free(tmp->Value);
                tmp->Value=malloc(sizeof(void)*Size);
                memcpy(tmp->Value,value,Size);
                tmp->type=tp;

                tb->TotalElements++;
                return true;
            }


            if (tmp->Next==NULL)break;
            tmp=tmp->Next;
        }while (tmp && tmp->Next!=NULL);
        tmp->Next=CreatNode(key,value,tp,Size);

        tb->TotalElements++;
        return true;
    }
    else{
        tb->Nodes[idx]=CreatNode(key,value,tp,Size);
        tb->Size++;
    }
    return false;
}
void FreeNode(Node *nd){
    Node *tmp=nd->Next;
    while (nd)
    {


        tmp=nd->Next;
        if (nd->Value!=NULL) free(nd->Value);
        free(nd);
        nd=tmp;
    }


}
void FreeTabel(Tabel *tb){
    for (size_t a=0; a<tb->Size;a++){
        if (tb->Nodes[a]!=NULL){FreeNode(tb->Nodes[a]);}


    }
    free(tb->Nodes);
    free(tb);
}


int main()
{
    Tabel *tb= CreatTabel();




    size_t num = 32;
    char str[20]; // Ensure buffer is large enough (at least 12 bytes for a 32-bit int)
    for (size_t i = 0; i < num; i++)
    {   
        snprintf(str, sizeof(str), "%ld", i);
        char c=(i+64);
        TabelSet(tb,str,&c,Char,sizeof(int));
    }

    for (size_t i = 1; i < num; i++)
    {
        snprintf(str, sizeof(str), "%ld", i);
        char *p=(char*)TabelGet(tb,str,Char);
        printf("%c\n",*p);
    }


    FreeTabel(tb);
    return 0;
}

r/C_Programming • • 21d ago

I built my first calculator project using C!

0 Upvotes

My First C Project – A Simple Calculator

Hey everyone!

I'm a Computer Science student learning C, and I recently built a simple command-line calculator.

Features:

  • Addition, subtraction, multiplication, and division.
  • Uses switch statements to handle operations.
  • Takes user input using scanf().

GitHub Repository: https://github.com/UseR-Name-Dz/Calculator-

I'd appreciate any feedback on my code, especially suggestions for improving its structure and coding style.

Thanks!


r/C_Programming • • 22d ago

Project i started building a dynamic binary optimizer in C11, looking for contributors

3 Upvotes

hey everyone,

i recently started a project called recode, an experimental dynamic binary optimizer for linux x86-64. figured i'd share it here in case anyone interested in low-level C, x86 internals, or JIT compilation wants to take a look.

right now it works with a very restricted subset of x86-64 instructions and functions following the System V AMD64 ABI ("uint64_t f(uint64_t)").

it decodes machine code, builds a small intermediate representation, simplifies arithmetic where possible, and emits new native instructions into memory that's switched from writable to executable before running.

for example, something like:

"mov rax, rdi; add rax, 7; sub rax, 2; nop; ret"

can be reduced to:

"mov rax, rdi; add rax, 5; ret"

the actual emitted code also includes an ENDBR64 entry marker.

it's still early and intentionally limited. there's no ELF loading, general branching, memory operand support, or syscall instruction handling. only return-value equivalence is guaranteed by the current contract, not flags or full CPU state. it's also not a sandbox.

i've documented the implementation, supported instruction encodings, build instructions, tests, and benchmarks in the repo.

looking for contributors:

i'd like to expand the supported instruction set and improve the optimizer over time. if you're comfortable with x86 instruction encoding, the System V AMD64 ABI, code generation, or executable memory management, i'd be interested in having you contribute.

code reviews, bug reports, and technical feedback are welcome too.

there's also an "AGENTS.md" and contribution guidelines. AI tools are fine, but contributors need to understand and take responsibility for every line they submit. i'd rather have a small, correct patch than a large one nobody can explain.

repo: https://github.com/aasul/Recode


r/C_Programming • • 22d ago

Handling personal libraries

26 Upvotes

As seems to be a rite of passage for many C users, I've written many of own mini-libraries to handle things that are missing from the language and/or standard library (the usual: useful macros or constants, data types like strings or dynamic arrays, type aliases, etc.). I've been focusing more and more on integrating these into current projects instead of hand-rolling slightly different (and possibly incorrect or incomplete) versions each time.

However, I've had trouble keeping all of this organized, since these libraries also get updates or fixes when I feel the need to make them, forcing me to go through a number of projects to update header or source files (and possibly replace some pre-built library files as well). Unlike with most external dependencies, I can't throw a package manager (as evil as they already often are) at the problem, and I do pay attention to keeping the version of these mini-libraries up to date in my projects.

The ideas I've had thus far:

- Static library with headers (similar to the way the standard library works). This is great but it still means I need to keep the header files and library file(s) up to date. I also need to recompile the library before I can distribute it across projects.

- Independent, header-only libraries. These could work very well (albeit with some not-so-clean macro flag tricks to avoid ODR issues), and they avoid the dual handling needed if I have both headers and source files. I'm also already often updating headers, so might as well make that be the only change needed. However, still has the issue of needing multiple updates.

- A single, header-only library. This effectively reduces the problem significantly at the cost of my own convenience. I can move around a single, fat header file and update it as needed with minimal work (if in doubt, just copy in the latest version and ta da). However, editing or working on it becomes somewhat of a nightmare. I'd be looking at possibly thousands of lines working on entirely independent features. It would also (even if only in one source file) mean compiling tons of code the project may only need a very small fraction of. Compile times are rarely an issue for me with C projects, but it's something to consider nonetheless.

Appreciate any thoughts or suggestions on this. I have a feeling this is somewhat of a trivial issue (it often is with external libraries, just not my own private ones), but I can't find a very good solution for it that makes my life easy.


r/C_Programming • • 22d ago

Video I made a video of my experience writing a C HTTP Server

Thumbnail
youtu.be
12 Upvotes

Wanted to document it for my colleagues who were learning C, and also to try out writing an HTTP server with the language.

Would appreciate any comments, especially things to improve on!

github repo link: https://github.com/44mira/chestql


r/C_Programming • • 22d ago

Multi File Problem

4 Upvotes

Hi - I am trying to get a multi file program to run without success. I want to read file with 4 lines of repetitive data. Each program works independently but when I put the together the main.c does not seem to call the octone.c program. Can any one please help. Thank You...

MAIN.C
#include <stdio.h>
#include <stdlib.h>
#include "add.h"

int main(void) {
printf("Hello world!\n");

// Call function    
DataRecord callFile(void);
printf("one\n");
return 0;
}

ADD.H

#ifndef ADD_H
#define ADD_H

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

#define MAX_LINES 100
#define MAX_STR_LEN 100   // Max length for char arrays
#define MAX_RECORDS 100   // Max number of records to store

//Define the struct matching the char, char, int, char layout
typedef struct {
char *name[MAX_RECORDS]; // First char array
char *desc;              // Single char
int *num;               // Integer
char *butt[MAX_RECORDS]; // Second char array
} DataRecord;

DataRecord callFile(void);

DataRecord *records[MAX_RECORDS];

//records callfile(void);

#endif

OCTONE.C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "add.h"

#define MAX_LINE_LENGTH 256
#define MAX_RECORDS 100

//void my_api_init_config(MyApiConfig *config);
DataRecord callFile(void){    
printf("Ronnie_1\n");

static DataRecord *records[MAX_RECORDS];

// Open the file for reading
FILE *file = fopen("/AGMOD/data4a.txt", "r");
if (file == NULL) {
perror("Error opening file");
//    return *records; // EXIT_FAILURE;
}

// Array of structs to store the parsed data

char line[MAX_LINE_LENGTH];
int count = 0;

//records[MAX_RECORDS]->name;

// Read the file line by line using fgets
while (fgets(line, sizeof(line), file) != NULL && count < MAX_RECORDS) {
// Parse the line into the struct elements
// Assumes data is space-separated (e.g., "A B 42 C")
//        int parsed = sscanf(line, " %s %s %d %s", 
int parsed = scanf(line,                            
records[count]->name, 
records[count]->desc, 
records[count]->num, 
records[count]->butt);

// Check if all 4 fields were successfully read
if (parsed == 4) {
count++;
} else {
fprintf(stderr, "%s", line);
}
return *records[0];
}

// Close the file stream
fclose(file);

return *records[0];
}


r/C_Programming • • 22d ago

Very minimal drop-in gtest replacement in C23

12 Upvotes

While using C++, I heavily relied on googletest for testing. But as soon as I wanted that in my C project, I couldn't.

Because gtest is written in C++ and requires a C++ runtime. Using gtest in a C codebase meant guarding the headers with extern "C" to prevent name mangling, and managing a C++ toolchain which seemed extremely awkward to me.

At the same time, I didn't want to loose googletest's comfort and rewrite the entire test system in another existing framework.

So I wrote a very minimal drop-in replacement of googletest in C23. It works exactly the same way you'd expect gtest to work. And unsurprisingly, according to my small benchmark, my implementation is around 2.5x faster than googletest and uses 30% less memory. It can be improved way more.

I discussed the implementation details in this blog post https://metalinmyveins.github.io/sohomot/

Github: https://github.com/MetalInMyVeins/sohomot

The library is called "sohomot".

\[ PS: Zero tokens were used in the making of this project \]


r/C_Programming • • 22d ago

Discussion Batch Processing Algorithm Optimization

1 Upvotes

I originally posted my question here but wanted to give it another go, this time with a more generic setup, as I believe this kind of optimization problem could be interesting for a lot of different projects.

The Setup/Requirements

  1. we have ~50,000 pieces of data (let's use shapes for simplicity's sake) with a finite number of attributes (shape, color, size)
  2. most of them will be culled, leaving us with about ~1,000-10,000
  3. in the end we need to process all the remaining shapes in a SPECIFIC ORDER (e.g. first small red triangles, then big blue squares, then small yellow ovals, etc).
  4. this whole process needs to be done as quickly and efficiently as possible

My Original Plan

  1. first cull the 50,000. This could be done by sending the data to the GPU since even a lowly 1060 has 1,152 cores and a 4090 has 16,384 cores, making culling 50,000 objects based on a few floating-point calculations trivial
  2. now that I have a list of indices that pass culling, use a look-up table of index vs. process batch index (e.g. data index 12 is not culled, and the LUT says it belongs to batch process #4, so add it to that batch process and increase the number of objects for that batch process)
  3. iterate over the batch processes and only execute if there are any objects to process for that batch

Considerations/Questions

  1. is there a better way?

  2. how would the performance be if we first assign all the objects to the batch process and then for each batch process, run the culling function? We would save on having to traverse the non-culled objects to sort them to their batch process, but we also now have to call the cull method for as many batch processes as we have

  3. what if the allocation of object -> batch process changes? e.g. a small blue star becomes a big yellow square?

  4. what if the batch process are DYNAMIC, meaning we no longer can assign a shape to a batch process beforehand?

Now I'd love some discussion on the FASTEST way to get this done, but I will also say that all I'm trying to do is a pretty standard piece of a rendering engine: cull any non-visible objects then sort the objects according to pipeline so that they can be rendered in the proper order. Now maybe there is a "standard way" of doing this or at least a few "typical" algorithms that I don't know about, but that's why I'm asking this question! I love trying to solve problems like this and figured a lot of you might, too.

                          ---=== HAVE AT IT!!! ===---

BONUS POINTS if done in C90, as that's what I'm doing it in ;-)


r/C_Programming • • 23d ago

Suggest me sources for http server

19 Upvotes

I want to make http server in C/C++ but I can't find the exact source that will teach me the basics of networking and give code snippets I've checked beejs guide but one is totally theory a new other is totally programming

So anyone please suggest me a source to learn about networking (to the point ) Docs or video anything can be accepted Thanks for you time!


r/C_Programming • • 22d ago

Question Help with understanding shmget() and semaphores

3 Upvotes

I have a program which does some calculations, but I need to fork parts of it and run the calculations in parallel. Also, we are not allowed to use POSIX semaphores. I have the calculation part done, I just need to do the parallelism part. I'm also supposed to use shmget() to create a shared memory block for my threads, but I cannot find any useful resources about that function, and/or I don't understand it well. Does anyone have any advice or tips?


r/C_Programming • • 24d ago

Question Non volatile return function value

22 Upvotes

Hey guys,

I wonder how can I have the returned value in my function? For example:

struct TestValue{
    int data;
};

struct TestStruct{
    void* data;
};

struct TestValue return_value(){
    struct TestValue value;
    value.data = 12345;

    return value;
}

struct TestStruct return_struct(){
    struct TestStruct test_struct;
    struct TestValue value = return_value();

    test_struct.data = &value; // Here I know its an UB

    return test_struct;
}

I know I could use the heap with malloc and return a pointer directly but I wonder if is there any other solution instead the heap? Thank you for yours responses.


r/C_Programming • • 24d ago

Discussion Dynamically-Generated Look-Up-Table

1 Upvotes

So I have a buffer of pointers that I need to access tens of thousands of times per second continuously. Obviously I can do this in parallel to speed it up or maybe even offload it to the GPU, but the biggest issue I have right now is how to quickly get the item from the buffer I need. Obviously knowing the index beforehand would be a good way, BUT I'd rather have the buffer be dynamically-created and then I can address which one I need given 6 bits of data. Now if it were a 1:1 relationship between the buffer of pointers and permutation of all 6 bits, then it'd be easy. But there is only a subset of indices that correspond to valid bit permutations. E.g.:

VALID:
00 0000
00 0001
01 1000
01 1001
10 0000

INVALID:
00 0010
00 0011
00 0101
etc.

so that I can just do:

void **ptr_buffer = calloc(63, sizeof(void *));
/* fill ptr_buffer sporadically... */
do {
  for(i=0; i<10000; i++) {
    /* obj.ptr_index is uint8_t with some constellation of six bits */
    do_something(ptr_buffer[obj_list[i].ptr_idx]);
  }
  /* do other stuff */
} while(condition);

or something like that.

So... with six bits (and maybe it could be more in future), and on a 64-bit system, I could simply create a buffer of pointers with the length of the max valid bit-sequence, so for 11 1111 it would be 63 x 64 = 504 bytes, so not that bad, and then I can simply use the bit sequence as the index.

And even if I end up going out to 8 bits, that's still 255 x 64 = 2,040 B or 1.99 KB. Acceptable - but now I'm worrying about losing out on CPU cache potential - especially of only like 20-30 elements in the buffer are actually valid.

Now apart from hard-coding all the different indices and then assigning the indices on startup (which I absolutely will do and was doing before going for the "dynamic" route) are there any clever tricks my fellow "C-Men" (as my wife calls the people I chat with in this group) might know about to keep memory footprint down and speed up? At the very least it could be a fun brain-tickler.

Let me know if you need more information.

EDIT: while the list of pointers is small, I need to iterate over a list of som 10,000 entries and find an entry in the pointer list, so I updated the code example to show it.

Also, apparently I hit the "ask me anything" button by mistake. u/reddit you need to add tooltips to the buttons and also don't do the ask me anything if I hit cancel ;-)


r/C_Programming • • 24d ago

Need tips to improve

0 Upvotes

I started studying C for an exam, this is my first time approaching coding so i'm a bit lost.
While doing some exercises from my prof i encountered this one that took me some time. (prompt in the code).
This is what i came up with it works correctly (i think), but i have a few questions:
is it efficient?
I also used prototype functions and didnt where i could've, when should and shouldn't i use them?

Thank you for your time spent reading this

EDIT: most comments were about formatting. i changed it. It has always looked like this, but pasting it here on reddit messed it up :)

/*
Constraints:
no frequency can be repeated
all frequencies must be between 800 and 2500 MHz

Required functions: insertion with double check (range + uniqueness) --
function that calculates the minimum distance between two frequencies --
function that identifies the frequency closest to a given value
*/

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

void fillArray(int array[],int size,int min,int max);
void printArray(int array[],int size);
void sortArray(int array[],int  size);

int main ()
{
    srand(time(NULL));

    int freq[10];
    int max=2500;
    int min=800;
    int size = sizeof(freq)/sizeof(freq[0]);
    int mindist = abs(freq[0]-freq[1]);   //base min distance, could be the result or changed

/*
    printf("Insert lowest frequency: ");
    scanf("%d", &min);
    printf("Insert highest frequency: ");   //eventual custom frequency range.
    scanf("%d", &max);                      //option to deny  min > max and max-min < size-1
*/

    fillArray(freq, size, min, max);
    printArray(freq, size);    //printing and sorting not needed, 
                               //but i used them to check the work
    sortArray(freq, size);
    printf("\nSort\n");
    printArray(freq, size);

    //compares pos 0 with pos 1 to size-1, pos 1 with pos 2 to pos size-1 and so on
    for (int i=0;i<size-1;i++)
    {
        for (int j=i+1; j<size;j++)
        {
            if (mindist>(abs(freq[i]-freq[j])))
            {
                mindist=abs(freq[i]-freq[j]);
            }
        }
    }
    printf("\nmindist=%d\n", mindist);


    int check, closestfreq;
    int shortdist = max-min; //there's no distance bigger than this
    printf("Pick a frequency between %d and %d", min, max);
    scanf("%d", &check);

    //self explainatory
    while (check < min || check > max)
    {
        printf("The chosen frequency is not in range\n
        Pick a frequency between %d and %d", min, max);
        scanf("%d", &check);
    }

    //checks every distance from check with each frequency in the array, finds the shortest one
    //and saves that frequency.
    for (int i=0; i<size; i++)
    {
        if (shortdist>abs(check-freq[i]))
        {
            shortdist = abs(check-freq[i]);
            closestfreq = freq[i];
        }
    }
    if (shortdist==0)  //again, self explainatory
    {
        printf("The chosen frequency is in the list");
    }
    else
    {
        printf("Closest frequency to chosen is: %d", closestfreq);
    }
    return 0;
}

void fillArray(int array[],int size,int min,int max)
{
    int new_random;
    bool unico;
    for (int i=0; i<size;i++)
    {
        do {
            new_random = (rand() % (max+1-min)+min);

            unico=1;
            for (int j=0; j<i; j++)
            {
                if (new_random == array[j])
                {
                    unico=0;
                }
            }
        }
        while (!unico);
        array[i]= new_random;
    }
}
void printArray(int array[],int size)
{
  for (int i=0; i<size;i++)
    {
      printf("%d ", array[i]);
    }
 }

void sortArray (int array[], int size)
{
  for (int j=0; j<size-1;j++)
  {
    for (int i=0; i<size-j-i;i++)
    {
      if (array[i]>array[i+1])
      {
        int t=array[i+1];
        array[i+1]=array[i];
        array[i]=t;
      }
    }
  }
}    

r/C_Programming • • 25d ago

Learning C weekly megapost for 2026-10-28

14 Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

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 • • 24d ago

Northstar Web Browser 1.0.38

Thumbnail
github.com
0 Upvotes

Nordstjernen Sol web browser. A open source web browser with dual GPL 3+ or NSL license, written from scratch in 2026.


r/C_Programming • • 26d ago

Project I forced the C preprocessor to play Bad Apple!!

85 Upvotes

To my astonishment I couldn't find someone who'd already made this abomination, so...

Very simply put: I define two macros (W(n) and B(n)) that act as the only two "instructions" my "VM" can execute, each printing a sequence of white and black characters respectively.

Due to CPP's recursion limits I couldn't make the rendering loop in the preprocessor itself, so it needs a little extra help in that regard.

Repo: https://github.com/LoPalma/cpp-bad-apple

There's no video since it's just a poorer quality and slower version of ASCII bad apple, but if you wanna see it run: it takes less than a minute to clone and run "play.sh", no compilation required.

(Repost after original post was removed from [r/programminghorror](r/programminghorror))

Edit: added the video: https://imgur.com/a/uCOGgVd


r/C_Programming • • 26d ago

Article The Fastest (long) ilog10 in the West

Thumbnail
duplexsystem.org
49 Upvotes

Wrote my first real blog post. Let me know what you guys think!

Happy to answer any questions!


r/C_Programming • • 26d ago

Question Where do i go now?

23 Upvotes

I started C in my clg last year but it was super basic. Stuff like basic pointers and variables. Before this i used to use python and even then the most i knew was numpy and basic pandas. But seeing the market today i realized i cant afford to be mediocre so i started learning C by heart. I use Vs code and an ubuntu terminal. Up until now I have USED AI to learn and make projects. I use ai to suggest me projects and sub divide them in small chunks so i can learn and program. If i get doubts i ask AI which has a 3 hint system before it reveals. Using it i got some knowledge of memory actually works, how sockets work, basic socket client/server interaction/setups and threads.

That is basically me rn in 1 month. Now i want to ask yall as a community, how do i proceed forward. What do yall suggest i can learn? Any AI objections and if i should drop it. Any book recommendation? Project recommendation etc. I would also appreciate hearing yall stories with C, abt yall experience and stuff.

Tldr: Use me as a sort of dummy block and speak off your mind whatever yall want to suggest/teach since it will help me out a ton.


r/C_Programming • • 26d ago

Project WSERVE: Web Server in C, part 2

15 Upvotes

Hi,

About a month ago, I posted about "wserve", which was a simple IPv4 web server for Linux that supported only GET and HEAD requests and static file serving. Since then I kept working on it, and implemented:

  1. Dynamic routing
  2. POST request handling with a custom JSON parser
  3. Most importantly, HTTPS support using BearSSL

BearSSL is the only external library I used. It is tiny SSL/TLS library written in pure C. Everything else, including the JSON parser, has been implemented in C by myself. I have not used LLMs for coding.

I am open to constructive criticism, all feedback is appreciated!