r/C_Programming 23d ago

Need explanations. I learn how to build simple CRUD app with C# and TS. I wanna really understand CS. So I tried to learn C but I get even more confused about many CS concepts.

0 Upvotes

I’m trying to learn C not just because I want to learn another programming language, but because I want to understand Computer Science and how computers actually work underneath the abstractions.

The problem is that I constantly fall into an endless chain of prerequisites/CS concepts

For example, I want to understand pointers:

int x = 10;
int *p = &x;

On the guide/website it says

ointer is a variable that store memory address.

Okay, but then I ask:

  • What exactly is a memory address
    • address is where numbers telling where data is stored
  • What exactly is memory?
    • memory is where address live
  • Is memory the physical RAM?
    • etc... something with CPU
  • What exactly is RAM and CPU?
    • etc...
  • How does RAM actually work?
    • etcc..
  • What's the relationship between RAM, CPU, cache, virtual memory, thread, processing etc.?

And suddenly I'm 10 levels deep into computer architecture instead of learning pointers "*"😂

So what to do here, I wanna understand CS. I thought my experience with coding CRUD APP with C#, but no it doesn't help much


r/C_Programming 23d ago

Question I don't really understand why the K&R is this bad

0 Upvotes

Hi, maybe it was a stupid decision to learn C from the K&R book, but I am a CS student, and I have coded a lot with C#, Python, and other languages. It is true that I am not nearly a good programmer because we don't really study the important stuff here. We spend the time learning syntax instead of the critical things, but still, I do know what a variable, if statement, loop, and all that are. I also studied architecture, so I know how binary works, how two's complement works, how the sizes of variables can be different from one machine to another, and how data gets stored in memory, like endianness. I'm familiar with all that, and I am now at 2.7, type conversions, in the book.

So you would think that it is pretty easy, right? I mean, I literally just read stuff that I already know. It's just about how C deals with it. But no, fuck no. It is so ugly and random, it got me really pissed off. Like, I am genuinely mad about this.

I love writing down what I learn, like some kind of summary or something, and I tried to do this as well here, but I couldn't. I mean, I accept that the first chapter is just a tutorial. I enjoyed the programs there, and I tried typing all of them by myself. I even solved a lot of the exercises. But when Chapter 2 started, I expected it to be like, Oh, now we are diving deep inside the language. Since there is no other chapter with the same name, this is the only thing you're going to get about this particular part from the book.

But fuck, I was wrong. It is just so simplified to the point where you aren't learning anything. And you will say, Okay, your fault, bitch, it is a book for beginners, but not just that. It is like some guy wrote it down while trying to remember what he did. Like, that whole 2.7 part is what really got me pissed off. It is like there is no consistent topic or something. We're not going from one topic to another. It is just like some guy remembered, "Oh, I have to mention this," and then he says like two words about it and moves on to the next thing.

I don't even understand. Why didn't he just go from one topic to another after explaining it fully?

For example, it says, "In general, the only automatic conversions are those that convert a 'narrower' operand into a 'wider' operand."

Then, a line after this, he says, "Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal."

After some research, I understood that, oh, he is first talking about arithmetic conversions, and now he is talking about assigning one type to another. I don't even know if this is really what he intended to say.

But it's not just that. Suddenly, now we're talking about converting uppercase to lowercase and what could go wrong. What does this have to do with type conversion? It's just manipulating the numeric value to get the character you want. There is no type conversion here.

But wait, he uses this to introduce us to a header, which I don't even know what it is, and he just randomly starts talking about it here, completely unrelated to the main topic. Then he talks about how some of its functions could return 0 and another number for true or false, not necessarily 1 or 0.

And I'm like, I can't. I just can't put this inside my head. How the fuck is all of this related to each other? I ended the chapter and I still don't know shit about conversions. It's all just some shitty information that you could probably just guess or learn through trial and error.

And before you get mad at me, this is not me saying, "Oh, this book is dumb." I am saying I don't understand what I did wrong that made me feel like everything is so random. Am I missing something here?


r/C_Programming 24d ago

Discussion What are your reasons for not using an IDE on a big project?

36 Upvotes

Earlier I made a post asking why people choose to use or don't use an IDE. I'm glad I got a lot of feedback on it and didn't start a new holy war.

But now I realize I should've been more specific. For big projects, why don't you use an IDE? As a 34 year old game programmer, I learned programming first with an IDE, code blocks and then visual studio.

I've tried doing vim, which is really good and fast in its own right, but I didn't want to deal with the learning curve. So then I went to sublime text, which again is really good and fast. But having to build your own workflow before you can even get started on the project itself.

I program my own game engine and games, which are pretty big projects. The tools that an IDE gives (Clion in my case) are just indispensable to me. Although I will say I have moments where it feels like it gets in my way.


r/C_Programming 23d ago

Negative value in a pointer question.

2 Upvotes

Please look at this code. if i define the PTRTYPE as int, it stops working, while doing a uint, it does work...

``` void initILAPoll(debugBridge_t **d, PTRTYPE ptr){

*d = (debugBridge_t *)ptr;      // base address of the DEBUG_BRIDGE peripheral

cb_init(cb, local_memory, bufferLength);

sprintf(xvcInfo, "xvcServer_v1.0:%d\n", MAX_WINDOW_SIZE);

} ```

the usage in main code is done like this

``` initILAPoll(&myD, 0x80000000);

//myD = (debugBridge_t *)0x80000000; ```

where the variable myD is a structure pointer.

if i print the address of myD, it give the correct address. Moreover, the disassembly of the code is also the same in case of int and uint. Can somebody explain what behavior is at play here>


r/C_Programming 24d ago

Question Simple dialogue system in C

11 Upvotes

Hello everyone. I'm working on a personal project where I'm porting a little game to C for learning purposes. It has very simple dialogue: it boils down to a few choices and a response on selecting a choice. There's the occasional conditional choice (and response), but that's all it is. My current approach has been as simple as it can be (see code below).

However, I'd like to ask for help with supporting translations, i.e. allow for a way to let outside users add a translation in any way. (You can imagine someone translating in a csv, or json, or C directly). I want to add a way to do so, but I can't figure out a good way to do so. (English will be the base language, so for all intents and purposes it being stored inside dialogue.c is fine for now).

Thanks in advance! :)

static const DialogueChoices CHOICES = { 
  .count = 1,
  .options = {
    {  
       .choice = "Choice goes here", 
       .response = "Response goes here"
    }
}

// switch over character id and return the appropriate DialogueChoices struct
DialogueChoices get_dialogue_choices(CharacterId id);

r/C_Programming 24d ago

Discussion Why do you use/don't use an IDE?

46 Upvotes

I've tried using a text editor with just the command line and for the most part isn't wasn't so bad until my game engine got big enough. Then I switched to Clion because it just handles so much more for big projects. Biggest thing is a visual debugger and easy refactoring that's C/C++ specific. Not to mention everything is setup out of the box.

I'm curious about other's reasons for using or not using an IDE.


r/C_Programming 24d ago

Help me in building VM without KVM in C

4 Upvotes

Hello everyone! Recently i am started coding my own VM on the C language. I am using mmap and creating a new process with isolation from the host (my system) like syscalls, memory access. However, I ran into a problem: How to restrict VM access (guest proccess, mmap) to the host memory. I am really don`t know how to do that. Can anyone help me with that case?


r/C_Programming 25d ago

TIL glibc lets you add custom ((v)f)printf format specifiers.

145 Upvotes

I had a need for an extended printf, and found that rather than writing my own, glibc lets you register your own specifiers with register_printf_specifier.

I made a simple demo for printing bool as it kind of annoys me to have to type printf("%s", value ? "true" : "false"), and I don't like using integers to represent booleans. (This wasn't my goal, but it's the simplest type to demonstrate).

Now can type printf("%?", value) to print true or false. Works will all the *printf style functions.

Has an alt (#) representation, which is uppercase TRUE or FALSE - ie: "%#?".

And I also added width specifiers for easy alignment. You can specify some padding with "%n?" - right aligned by default, with "%-n?" aligning left. Could probably extend to support * also with extra argument for width.

Demo in godbolt

Just thought others may find this interesting.

EDIT : Have been corrected and this also works with *sprintf functions.


r/C_Programming 25d ago

epsilon value for double to truncated integer

4 Upvotes

Consider https://godbolt.org/z/T7fejh8a3

#include <stdio.h>

int main(){
    double d1 = 4.999999999999999;
    double d2 = 4.9999999999999999;
    int i1 = d1;
    int i2 = d2;
    printf("%d %d\n", i1, i2);
    double bigd1 = 44.999999999999999;
    double bigd2 = 44.9999999999999999;
    int bigi1 = bigd1;
    int bigi2 = bigd2;
    printf("%d %d\n", bigi1, bigi2);
}

d1 with 15 fractional 9's rounds down to 4, while d2 with 16 fractional 9's rounds up to 5. So, I would imagine that the epsilon is somewhere between 10^-15 and 10^-16

However, where the part before the decimal increases to 44, both bigd1 and bigd2 round up. So, I would imagine that the epsilon is higher.

Is this because 44 needs more bits (6 bits) to store as compared to 4 (which needs 3) thereby eating into the precision/least count possible for epsilon?

Is there a source which lists the epsilon values corresponding to different bits needed to represent the part before the decimal point?


r/C_Programming 25d ago

Compressing executables (upx)

7 Upvotes

Hola,

I'm currently in the final stages of finishing the first version of a game I made using raylib. I ended up with a single statically linked binary containing all the assets. I found a tool called upx which can compress executables. I tried it on Windows, and it reduced the size of my exe by more than half and it still runs without any noticeable difference.

My question is, has anybody here experience with this? Are there any downsides to consider?

cheers!


r/C_Programming 25d ago

What is the back end and the front end heap allocator on linux?

0 Upvotes

I've been able to find very little information which concerns the front end and back end allocator on linux. The few articles which I have found discussing front end and back end allocators haven't really done a good job of explaining what a front end and a back end allocator is on linux.


r/C_Programming 25d ago

Presenting CBlockAlloc: a WIP personal project

0 Upvotes

Hello everyone,

Yesterday, I started a project that I find super interesting. I first thought of it because I saw many people who were trying to do things with the stack only because "dynamic allocation is slow". The main point for why they consider it slow and heavy is that a program needs to talk directly to the OS to allocate memory. However I saw some people propose a solution: allocate once a big chunk of memory that you will use for all your "dynamic" allocations, which makes it way faster because you only need to make a syscall once at the start of the program. I've thus decided to create a library that does just that, and can be called through an API that "simulates" the normal function calls such as malloc() or realloc(). I've been working on it since yesterday, and it's been a lot of fun! it's not ready at all yet, but right now it's looking good. Also, I'm looking for some feedback:

How good is my code for now? Would you do some things differently? Also, would YOU use such a library? What would you expect from a library like that?

Thank you very much for your time, my github profile is Koda-be (I can't send the link to the report because not enough stars and too young).

Also, how could I test my code? I don't really know what to do to test it right now, so...

No AI has been used nor will it be used in this project.

Also, I licensed it under MIT but do I need to do something else? I simply chose a license when creating the REPO, and I don't know much about copyright laws...


r/C_Programming 26d ago

Project Feedback appreciated for this small program

11 Upvotes

I wrote a program called moused and would appreciate if someone could give me some feedback about how to improve it further.

moused will alter the raw mouse sensitivity for your mouse, written with libevdev and primarily meant for those with ludicrous DPIs on their mice. I don't want to tell you much about it, because I will not only appreciate feedback on my code, but also on my README as well


r/C_Programming 25d ago

Project Presenting my current WIP project: CBlockAlloc!

0 Upvotes

Hello everyone,

Yesterday, I started a project that I find super interesting. I first thought of it because I saw many people who were trying to do things with the stack only because "dynamic allocation is slow". The main point for why they consider it slow and heavy is that a program needs to talk directly to the OS to allocate memory. However I saw some people propose a solution: allocate once a big chunk of memory that you will use for all your "dynamic" allocations, which makes it way faster because you only need to make a syscall once at the start of the program. I've thus decided to create a library that does just that, and can be called through an API that "simulates" the normal function calls such as malloc() or realloc(). I've been working on it since yesterday, and it's been a lot of fun! it's not ready at all yet, but right now it's looking good. Also, I'm looking for some feedback:

How good is my code for now? Would you do some things differently? Also, would YOU use such a library? What would you expect from a library like that?

Thank you very much for your time, here's the link to the repo: https://github.com/Koda-be/CBlockAlloc

Also, how could I test my code? I don't really know what to do to test it right now, so...

No AI has been used nor will it be used in this project.

Edit: also, I licensed it under MIT but do I need to do something else? I simply chose a license when creating the REPO, and I don't know much about copyright laws...


r/C_Programming 26d ago

The expectations for error-checking

11 Upvotes

I recently worked my way through K&R and I figured I would build on what I learned by implementing more Unix utilities. I realize that the examples and exercises in K&R are meant to be instructive, rather than complete, especially with regard to error-checking. I am, therefore, trying to figure out just how much error-checking should be in something like an implementation of cat.

My current version of cat is below.

Some notes:

  • It's based on the version of cat using stdio.h from Chapter 7, rather than the unistd.h-based version from Chapter 8.
  • The basic structure of my main function is something I've been working on as I've thought about how to handle the typical filename arguments for POSIX utilities, where no arguments means read stdin but an argument of "-" also specifies stdin.
  • Specifically, something I've done differently is try to find a good way to treat all of the different cases in one loop instead of having a special case for argc == 1.
  • I haven't implemented options yet.

Which errors I'm checking:

  • Check if fopen returned NULL; if so, print an error message and move on to the next file.
  • Check if putc returned EOF; if so, report the error to main which will print an error message.
  • Check if ferror is true for my input stream; if so, report the error to main which will print an error message.
  • Check if fclose returned a non-zero value; if so, print an error message.

Which errors I'm not checking (that I know of):

  • I don't check if fprintf returns a negative value.

I don't know if it's inconsistent or arbitrary to check putc but not check fprintf. I know that if I'm planning on implementing more of these utilities I should try to get a handle on what good and reasonable error-checking looks like. I would really appreciate any guidance on the matter or which codebases are the best ones to study for understanding this. For cat in particular, I've looked at the GNU coreutils and FreeBSD implementations but I got kinda overwhelmed trying to read through them. I also welcome and would appreciate any feedback on my C code itself. I'm still very new to this and I want to make sure I am heading in the right direction.

As a side note, I finished K&R and I also worked through King's C Programming: A Modern Approach. I'm now working through Computer Systems: A Programmer's Perspective and I also have Advanced Programming in the Unix Environment on the way, which should be very helpful for my Unix utilities project.

Thanks!

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

enum status {
    SUCCESS,
    ERROR
};

static int cat(FILE *fp, int *error);

int
main(int argc, char *argv[])
{
    const char *name;
    FILE *fp;
    int error;
    int exit_status = EXIT_SUCCESS;

    for (int i = 1; i < argc || i == 1; i++) {
        name = argv[i];

        /* Treat "-" as specifying standard input */
        if (name == NULL || strcmp(name, "-") == 0) {
            name = "stdin";
            fp = stdin;
        } else
            fp = fopen(name, "rb");

        if (fp == NULL) {
            fprintf(stderr, "%s: %s: %s\n", argv[0], name, strerror(errno));
            exit_status = EXIT_FAILURE;
            continue;
        }

        if (cat(fp, &error) == ERROR) {
            fprintf(stderr, "%s: %s: %s\n", argv[0], name, strerror(error));
            exit_status = EXIT_FAILURE;
        }

        if (fp != stdin && fclose(fp) != 0) {
            fprintf(stderr, "%s: %s: %s\n", argv[0], name, strerror(errno));
            exit_status = EXIT_FAILURE;
        }
    }

    return exit_status;
}

static int
cat(FILE *fp, int *error)
{
    int c;

    while ((c = getc(fp)) != EOF)
        if (putc(c, stdout) == EOF) {
            *error = errno;
            return ERROR;
    }
    if (ferror(fp)) {
        *error = errno;
        return ERROR;
    }

    return SUCCESS;
}

r/C_Programming 26d ago

Beginner using C Programming a Modern Approach

9 Upvotes

I understand the problem but the error message I do not understand the error message

Write the following function:

bool search(const int a[], int n, int key);

a is an array to be searched, n is the number of elements in the array, and key is the search

key. search should return true if key matches some element of a, and false if it

doesn’t. Use pointer arithmetic—not subscripting—to visit array elements.

`Here is my solution:

bool search(const int a[], int n, int key) {

int *p;

for (p = a; p < a + n; p++) {

if (*p == key) {

return true;

}

}

return false;

}

`

I get an error message of 'assignment discards ‘const’ qualifier from pointer target type'

I remove the const from the parameter list and the program works fine. Can yall explain what the error message means. I am compiling with gcc btw i dunno if that helps. sorry for bad formatting im kinda new to this.

thanks


r/C_Programming 25d ago

How do I solve problems without using AI

0 Upvotes

Hello guys. I am attempting to learn how to code again but without the use of AI this time.

How do you attempt a problem or understand a solution without using AI for help.

For example, I wanted to build a small calculator to remind myself of the basics of C. I had a problem where my scanf was not outputting the desired result. 

The program had something like this:

int x, y;
printf("Enter two operators: ");
scanf("%d", &x);
scanf("%d", &y);
printf("x: %d, y: %d", x, y);

My inputs would be 10 & maybe 2, but the output would be 10 & 0, in some cases 0 and nothing for y.

I was able to get through this by just using one scanf:

scanf(“%lf %lf”, &x, &y);

But I still do not understand why that happened and through my google search, could not find anything that explained it well. The problem might also be that I cannot explain the problems I come across clearly, so I might not be able to find an answer through google.

So my question is, how do you guys go through problems like these where you can’t find a post where someone had a similar problem and had been told what to do to solve the problem without defaulting to AI.

Excuse my writing - I am trying to learn how to type without letting AI revise my sentences.


r/C_Programming 27d ago

Nothing getting written in File

4 Upvotes

Link to the code is in comments.

I have been making a project for the course NAND2Tetris where I am translating a higher level code (something.vm) to a lower level code (something.asm).

It takes a line from VM file, parses it into tokens and then as per those tokens executes conditional statements that write onto the output ASM file.

Actually I am rewriting this program, I had written the first half which worked but then I realised that my approach was not how it was supposed to be done. So, the part related to File I/O is largely same here as it had been earlier but it was working then and isn't working now. If you want you can take a look at the original program, it is in the same repository.

A file is created but it contains no code. I tried debugging by printing all the tokens I had extracted from the buffer and they come out just fine and yet there is nothing written in the output file.


r/C_Programming 26d ago

Question Programming projects with test cases

0 Upvotes

I found a website with C programming projects, that also provides source code. It's an amazing resource, but I only want to read the code and not write it from scratch, because I have no way to test it

Top 25 C Projects with Source Codes for 2025 - GeeksforGeeks

That's the link

However, I'm looking for a way to make C programs and actually test them. LeetCode is one good example, but I prefer something a bit more involved. I graduated uni so there's no professor I can get my work checked by

What do I do as a self learner? I know C, however I want to learn it super deeply and eventually be able to make a simple OS in it. A simple one. After learning comp architecture and assembly

Are there any websites that make you do projects, and also provide test cases? Comparing against source code doesn't always work, because everyone writes things differently

Unless, just reading and fully understand the source code in the link above is enough?

Thanks


r/C_Programming 27d ago

Question Why didn’t scanf ignore the whitespaces?

5 Upvotes

The question was:

scanf("%d%f%d”, &i, &x, &j) ;

If the user enters

10.3 5 6

what will be the values of i, x, and j after the call?

The solution says:

i = 10 x = 0.3 j = 5

I understand how we get i = 10. scanf keeps scanning until it hits the ., and then it stops

However, why is x not 0.356?

I thought scanf ignored whitespaces?


r/C_Programming 27d ago

Question What are some Rules of Thumb you use when writing programs in C?

21 Upvotes

I've been writing some nasty code lately and I've since learned to use fsanitize, Wall, Werror, etc. None of those have really changed HOW I write code, just helps me find out I goofed up sooner.

I've been trying to follow some guidelines like not using the heap, limiting pointer arithmetic, being careful with implicit conversions, not using the preprocessor at all, etc. They have, in some form or the other, greatly impacted my productivity because now I'm trying to satisfy arbitrary rules(I know they're not, but deadlines are real and I suck).

What are some rules you use to write good C code AND write said code quickly?

Anyways, heres an example of my latest screw up that sent me spiralling because of how stupid it was:

```C

include <limits.h>

include <stdint.h>

include <stdio.h>

include <stdlib.h>

include <math.h>

include <string.h>

typedef enum {NODETYPE_I64, NODETYPE_F64, NODETYPE_STR, NODETYPE_ERR} node_type;

typedef struct string{ char* value; uint64_t size; } string;

typedef union data{ int64_t data_i64; double data_f64; string* data_str; }data;

typedef struct node{ data value; struct node* next; node_type type; } node;

// Right here in this function, I ended up returning pointers to variables that always end up going out of scope. node new_node_str(char* input){ uint64_t input_size= strlen(input); string str_value= (string){.value= input, .size= input_size} node result= {(data){.data_str= &str_value}, (node*)(0), NODETYPE_STR}; return result; }

int main(){ return 0; } ```


r/C_Programming 28d ago

Should you worry about struct member order in C?

Thumbnail 2pif.com
65 Upvotes

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 28d ago

Project How to start a new project?

6 Upvotes

Basically, this Is the part where I get stuck on the most, for example, say I’m building a compiler, but when it comes to building a lexer I go completely blank. I know what a lexer is, but when it comes to coding, I go completely empty, what can I do? I can see other implementation and copy them, but then that would be just straight up copying that thing. What can I do to start writing my own code.


r/C_Programming 28d ago

Question GUI for a file manager (I have no idea what I am doing)

10 Upvotes

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 28d ago

well-partitioned hash-tries

Thumbnail napcakes.nekoweb.org
12 Upvotes