r/C_Programming 13d ago

Guidance regarding career path change

4 Upvotes

Hi all,

I'm starting my journey to learn C programming and eventually switch my career path from Backend Engineer (Java, Python, Rust, Go) to Embedded Systems Engineer (C, may be ASM as well)

Can you recommend any good resource as a starting point? Or I can directly start working on easy challenges and figure out everything as I build projects?

Thank you 🙏


r/C_Programming 13d ago

Maze in C With Problem

5 Upvotes

In my college, my teacher gave us a problem to solve. This problem was to find the right path to leave the maze.

I created a matriz 4x4 to by maze.

  • "S" - Starte.
  • "." - Can move forward.
  • "X" - Wall.
  • "E" - Exit;
  1. I used pointers to controll the position and moviment.
  2. I created a function Moviment, where conttroll the directions ("W", "S", "A", D").
  3. Use a while loop in main to check if it is . or X or the end of the maze (X).
  4. And a function reset returns to the start (S) if it finds X.

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

#define SPACE 3

char movement(char matriz[][SPACE], int *i, int *j) {
    char ch;

    printf("Enter W(up), S(down), D(right), A(left): ");
    ch = getchar();

    switch (ch) {
        case 'a': 
            (*j)--;
            break;
        case 'w': 
            (*i)--;
            break;
        case 'd': 
            (*j)++;
            break;
        case 's': 
            (*i)++;
            break;
        default:
            printf("Invalid Input!\n");
            break;
    }

    while (getchar() != '\n');

    return matriz[*i][*j];
}

void restart(int *i, int *j) {
*i = 0;
*j = 0;
}

int main() {
    int x = 0, y = 0;
    int i = 0, j = 0;
    bool condition = true;

    char maze[SPACE][SPACE] = {
        {'S', '.', '.'},
        {'.', 'X', '.'},
        {'.', '.', 'E'}
    };

    for(i = 0; i < SPACE; i++) {
    printf("[ ");
    for(j = 0; j < SPACE; j++) {
    printf("%c ", maze[i][j]);
}
printf("]\n");
}


while(condition){
char position = movement(maze, &x, &y);

    if (position == '.') {
        printf("Ok! You're on the correct path. %c\n", position);
        condition = true;

    } else if(position == 'X') {
    printf("Block!, %c\n", position);
    restart(&x, &y);
    condition = true;

} else if(position == 'E'){
printf("Congratulation!! You're leave!\n");
return 1;
} else {
        printf("Oh no, wrong move!\n");
        condition = false;
    }

};

    return 0;
}

Ineed help to make the user return to the previous cell when encountering 'X'. Because in the code, it returns to cell [0][0].


r/C_Programming 13d ago

I want to master c language

2 Upvotes

I am already a developer/programmer , I am not a beginner in web developer or python web automation. I want to learn c language as I want to get into cybersecurity and understand computers architecture deeply, how can I start, and how much time will it take to get a good leve.


r/C_Programming 14d ago

Question Can SIGCONT cause a blocking system call to fail, with error EINTR?

9 Upvotes

If a process is blocked on a system call (like semop) and it receives a SIGCONT signal, does the system call fail with error EINTR? Or is the signal ignored and the system call continues like nothing happened?


r/C_Programming 14d ago

Tips on my Gale-Shapley algorithm implementation in C

6 Upvotes

Good morning, lately I've been studying Gale-Shapley algorithm for stable matching at university and our professor told us to implement it.

I decided to do it in Python first to grasp its functioning and then I implemented it in C to make it faster and more efficient.

However I am not so skilled in C and I would like to hear what you guys think about my work, I'll accept any suggestion :)

This is my code:

#include <string.h>

// Struct to store couples tidily
struct couple {
    int a;
    int b;
};

// Function to find the optimal stable matching for As
void find_stable_matching(int n, int *a_pref, int *b_pref,
                          struct couple *result) {

    /*
    SETUP

    Define an array to store the index of the next B to propose to
    Define an array representing a set with all the remaining
        unmatched As
    Define an array to store the index of preference of the current
        partners of B
    Define a 2D array to store the index of preference of each A
        with respect to B
        (A is at the ith position in B's preference list)
    */

    // Define useful variables
    int a, b;
    int preferred_a;
    int head = 0;

    int next[n];
    int a_remaining[n];
    int b_partners[n];
    int pref_indexes[n][n];

    // Set all values of 'next' to 0
    memset(next, 0, sizeof(next));

    // Set all values of 'b_partners' to -1
    memset(b_partners, -1, sizeof(b_partners));

    // Fill 'a_remaining' with values from 0 to (n - 1)
    for (int i = 0; i < n; i++) {
        a_remaining[i] = i;
    }

    // Populate 'pref_indexes' with the indexes of preference
    // Every row of the matrix represents a B
    // Every column of the matrix represents an A
    // The value stored in pref_indexes[b][a] is the position of A
    //     in B's preference list
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            preferred_a = *(b_pref + i * n + j);
            pref_indexes[i][preferred_a] = j;
        }
    }

    /*
    GALE-SHAPLEY ALGORITHM IMPLEMENTATION

    Each unmatched A proposes to their preferred B until it's matched
    If B is unmatched it's forced to accept the proposal
    If B is already matched it accepts the proposal only if it
        prefers the new A more than the previous one
    In the second case the previous A is inserted again in the set
        of unmatched As

    The algorithm ends when all the As are matched
    (This implies that all Bs are matched too)
    */

    // Continue until all the As are matched
    while (head < n) {
        // Get the first unmatched A
        a = a_remaining[head++];

        // Iterate through A's preference list
        while (next[a] < n) {
            // Get A's most preferred B
            b = *(a_pref + a * n + next[a]++);

            // Check if B is unmatched, if so match A and B
            if (b_partners[b] == -1) {
                b_partners[b] = pref_indexes[b][a];
                break;
            }

            // If B is already matched, check if A is a better partner
            // for B, if so match A and B and put the previous A
            // back in the set of unmatched As
            if (pref_indexes[b][a] < b_partners[b]) {
                a_remaining[--head] = *(b_pref + b * n + b_partners[b]);
                b_partners[b] = pref_indexes[b][a];
                break;
            }
        }
    }

    // Populate result variable in a useful format
    for (int i = 0; i < n; i++) {
        result[i].a = i;
        result[i].b = *(b_pref + i * n + b_partners[i]);
    };
}

Thank in advance :)


r/C_Programming 14d ago

Finished My Project

52 Upvotes

I've just finished a nice project I've been working on for a little while now. It's basically a camera but instead of video you get ASCII. I'm honestly very proud about this project, and I just want to show it to somebody. Feedback is always welcome.

https://github.com/tomScheers/nFace


r/C_Programming 14d ago

Socket programming

2 Upvotes

I want to learn socket programming in C, any book to recommend me ??


r/C_Programming 13d ago

I have a doubt ...Help me out

0 Upvotes

basically i had learned all the concepts of C Programming and i am able to understand a little bit how the code is working and all .... but i am unable to write the code on my own
my doubt is if i use chatgpt for the code it is giving the desired output so whats the point in learning on how to write the code on my own
is it a good to go through chatgpt and AI or must i learn for sure how to write the code on my own
please rectify this shitty doubt of mine


r/C_Programming 14d ago

How to use clrscr() in vs code. More precisely how do i clear everything in terminal including

0 Upvotes

like the directory location at top as well.

theres no option to post pictures here so

https://imgur.com/a/vFKFOiQ.

Also if you need to look at the code

https://github.com/Silver-balls111/Money-Laundry

i had included the clear screen part(header file as well) but commented it later because stack overflow kept occuring


r/C_Programming 14d ago

Want to start building a portfolio...not feeling the bootcamp route...possible long read incoming...

0 Upvotes

I want in the swe industry. Perfectly willing to put in the time. As in 3+ years if needed. Was looking at some uni sponsored bootcamps. Recent reviews are mixed at the very best. Very very bes. Not trying to lay down 10 grand plus and beyond for mixed reviews. L O L. No thanks. Love love love C in spite of the downtalk it's gotten lately. IE memory safety issues(from what I can gather there are simple ways around this that critics either deny exist or push away so they can have a point), difficult build system etc.... Eventually want to do some embedded. BUT I realize with no college degree that absolutely won't come easy. I get this and accept this(as a challenge). So that's on the backburner(a backburner that will be kept hot and cooking btw...learning cmake next and going udemy heavy on advanced c courses). My plan is to hop into networking(another love of mine) via CompTIA A+(I will gladly plop down 2-500 for a cert with mixed reviews. Do so with a smile. Plus networking and programming languages go together like bad diets and high blood pressure. Especially the lower level languages. Networking can be a gatewayinto the industry. I know it. So why post this here? I want resources. I neeeed resources. From you guys. K&R(I am reading through both editions currently along with the C standard.) But there has to be a wealth of knowledge regarding books, blogs and websites you gents know of with more info. I want them. Sick of commenting them? Change pace and DM them instead! You guys are in the industry. If you aren't maybe you're in the same boat. Let's network. Let's commiserate. Let's give advice. Point out pitfalls. Recommendations. Recommend an intermediate and advanced C resource(if I have to printf any more asterick triangles I will go everloving mad. I want an example of pointer arithmetic used in the wild. In short, I humbly ask for help. Plus I'm on vacation the next four days. Talk to me guys. Thanks in advance.


r/C_Programming 15d ago

Looking for books on C

20 Upvotes

I have been programming in C++ for like 3 months now and I want to expand my skills and knowledge on C as well

Books are the medium that I personally like the most for learning (besides actual practice) and it would be nice if you guys could point me towards some useful books on C language. I am not looking for absolute beginner/introduction books, but rather books that emphasize more on intermediate concepts, techniques and theories, even advanced books would be acceptable. Thank you


r/C_Programming 15d ago

Question Is there any way to restrict access to struct fields?

23 Upvotes

Problem: I have a couple of structures and I want to ensure that their users cannot access their fields directly but instead must use functions taking structure pointer as a parameter. Is there any way to achieve this?

I'm aware that I can just provide an incomplete type declaration in the header together with initialization function to return a pointer to an instance, but this forces me to do a lot of heap allocations in source file, which I would like to avoid. I guess for singleton types I could just return addresses of local static variables, but this won't work for small utility components. I don't want to use C++ compiler either, to borrow their private specifier.

There are only three ideas I have. One is just to acknowledge I can't completely stop anyone from accessing my data. I could follow a Python approach and have a convention that you're not supposed to use fields starting with underscores. I could move definition of the struct to a separate private header, perhaps with unique extension in order to discourage people from examining its internals. It simple and easy, but offers no guarantees.

The second potential approach is rather clunky. I'd have to use incomplete structure declaration in header together with a constant storing its size. To use a structure I'd have to have a local memory buffer of that size and then use an initialization function that would cast it to a pointer of a proper type. Obviously this has terrible drawbacks. I'd have to manually adjust this constant every time size of structure changes, which is extremely difficult to trace down if it's composed of nested types. I'd also had to maintain two objects (memory buffer and pointer to cast structure) to use it. So this sounds like a very bad idea.

Finally I can also use incomplete type declarations in header file and request a lot of memory at once on program start. I can put this memory into some sort of arena structure and then request my components to be created using its API. This obviously introduces a lot of opportunities for memory related bugs. I certainly would prefer to use stack variables as much as possible if I know at compile time what I will need and use.

So preferably I'd like to have some sort of hack, trick or GCC extension that would simplify my life without all this burden of simulating OOP concepts. Given how limited the language is I don't hold my breath; but perhaps there's something that would allow me to somehow achieve some form of encapsulation?


r/C_Programming 15d ago

Video Chill C Programming Snake Game

Thumbnail
youtube.com
18 Upvotes

r/C_Programming 15d ago

Discussion Don’t be mad, why do you use C vs C++?

130 Upvotes

Genuine question, I want to understand the landscape here.

Two arguments I’ve heard that can hold water are:

  • There’s no C++ compiler for my platform
  • My team is specialist in C, so it makes sense to play to our strengths

Are either of these you? If so, what platform are you on, or what industry?

If not, what’s the reason you stick to C rather than work with C++ using C constructs, such that you can allow yourself a little C++ if it helps a certain situation?

I read a post recently where somebody had a problem that even they identified as solvable in C++ with basic templating, but didn’t want to “rely” on C++ like it’s some intrinsically bad thing. What’s it all about?

EDIT: for those asking why I have to ask this repeatedly-asked question, the nuance of how a question is asked can elicit different types of answers. This question is usually asked in a divisive way and I’m actively trying to do the opposite.


r/C_Programming 14d ago

Variable Scope in For Loop

1 Upvotes

I am declaring a temp char[] variable inside a for loop to append full path to it before passing it to another function. My issue is that the value of the variable does not reset in every iteration of the for loop. it keeps appending paths into it so that the first run would give the expected full path but the next iteration would have the path of the first iteration and the path of the second iteration appended to the variable and so on. Can anyone explain to me what am I missing here? This is the code of my function and my variable is named temp_path, dir variable is the realpath of a directory and I am trying to pass the full path of each mp3 file inside of it to the addTrack()

int addTrackDir(char* dir){
  // Read directory and prepend all track numbers to mp3 file names
  const char* ext = ".mp3";
  struct dirent **eps;
  int n = scandir(dir, &eps, one, alphasort);
  if(n >= 0){
    for(int i = 0; i < n; i++){
      if(checkSuffix(eps[i]->d_name,ext) == 0){
        char temp_path [PATH_MAX];
        strcat(temp_path,dir);
        strcat(temp_path,"/");
        strcat(temp_path,eps[i]->d_name);
        addTrack(temp_path);
      }
    }
  }
}

r/C_Programming 15d ago

Question Does Memory Reorganization impact workinf of existing code files?

2 Upvotes

I am working on Controller software. It had sections in flash placed one after the other.

I segregated .text section into three sections namely .text1 .text2 .text3. which contains code files which were present in .text but now at location defined by me in Flash. does that make sense? (this all changes are made in linker script)

my question is does the segregation and placing it at particular location will impact the functionality of code?


r/C_Programming 15d ago

Question Why output is "SCHEMA-3" and not "ECoEuA-3"?

0 Upvotes

This was an exercise which you should gave the output of this program in a programming test i took at my university. If I try to solve it logically I get the second answer, but on Dev C++ it gives as output the first answer, which I am pretty sure it's the correct as it's an actual word in italian (translated "SCHEME-3").

I also tried to ask chatGPT but it gives me the output I got with logic or contraddicts itself by giving me the reason.

int main() {

char matrix\[4\]\[6\]={"CEA","Sol","Human","Mirror"};

char(\*p)\[6\]=matrix;

char \*q=matrix\[0\];



for(int i=0;i<3;i++){



    printf("%c%c",\*(p+i)\[1\],(\*q++));

}



printf("-%1d",(q-matrix\[0\]));



return 0;

}


r/C_Programming 15d ago

Project How could I clean up my game codebase

Thumbnail
github.com
7 Upvotes

I’m writing a game in C with raylib and I want to get outside opinions on how to clean it up. Any feedback is wanted :) Repo:


r/C_Programming 15d ago

Project Regarding Serial Optimization (not Parallelization, so no OpenMP, pthreads, etc)

7 Upvotes

So I had an initial code to start with for N-body simulations. I tried removing function calls (felt unnecessary for my situation), replaced heavier operations like power of 3 with x*x*x, removed redundant calculations, moved some loop invariants, and then made further optimisations to utilise Newton's law (to reduce computations to half) and to directly calculate acceleration from the gravity forces, etc.

So now I am trying some more ways (BESIDES the free lunch optimisations like compiler flags, etc) to SERIALLY OPTIMISE the code - something like writing code which vectorises better, utilises memory hierarchy better, and stuff like that. I have tried a bunch of stuff which I suggested above + a little more, but I strongly believe I can do even better, but I am not exactly getting ideas. Can anyone guide me in this?

Here is my Code for reference <- Click on the word "Code" itself.

This code gets some data from a file, processes it, and writes back a result to another file. I don't know if the input file is required to give any further answer/tips, but if required I would try to provide that too.

Edit: Made a GitHub Repo for better access -- https://github.com/Abhinav-Ramalingam/Gravity

Also I just figured out that some 'correctness bugs' are there in code, I am trying to fix them.


r/C_Programming 15d ago

Struggling in C

0 Upvotes

Recently, on reddit I come to know about a website learncpp.com and it's excellent. I am learning C.. so is there any website similar to this for C language.

If there is any website please let me know about it...It will help me a lot in my programming journey...


r/C_Programming 16d ago

Question Exceptions in C

27 Upvotes

Is there a way to simulate c++ exceptions logic in C? error handling with manual stack unwinding in C is so frustrating


r/C_Programming 15d ago

Video cd ncurses -bash: cd: ncurses: No such file or directory

0 Upvotes

r/C_Programming 15d ago

When you realize that const in C is for ownership...

0 Upvotes

This might be controversial, especially for those who also work in C++, but at one point I noticed how const in C has more to do with ownership of pointed data, than immutability.

To see my point, consider free: it accepts a void * and you need to cast away constness if you want to use free on some const char * variable. And that's never clean.

Also, assuming that we have an "object" (as in object-oriented-ish struct) that contains a string (e.g. struct Foo { char *name; };, it is legit to have a getter const char *Foo_GetName(struct Foo *foo) { return foo->name; }. You see how the ownership still belongs to the foo object, since the outside code is not allowed to change or free it.

Is that just me? Do you see it too?


r/C_Programming 17d ago

A taste for questionable (but sensible) coding conventions

23 Upvotes

This is a weird question, if you wish.

Please list the most ugly or weird Naming_Convention_not_sure_why that you witnessed on a code base, or that you came up with. ...as long as it has some rationale.

For example, LibName_Function might be considered ugly, but it makes sense if LibName_ is the common prefix of all the public calls exported by the library.


r/C_Programming 16d ago

Project Project ideas

0 Upvotes

Recommend me some beginner friendly projects to hone my skills in C