r/C_Programming

anonymously initializing static pointers in self-referential data-structures?

I have a recursive data-structure (a simple linked list for purposes of this example) and wanted to statically define a linked-list. The following works fine:

#include <stdio.h>
typedef struct mytype_tag {
    struct mytype_tag* next;
    char* data;
} mytype;

mytype a = {
    .next = NULL,
    .data = "a",
};
mytype b = {
    .next = &a,
    .data = "b",
};

int
main() {
    mytype* s = &b;
    int i = 0;
    while (s) {
        printf("%d: %s\n", i++, s->data);
        s = s->next;
    };
}

However, I have to explicitly define/declare a and then have b take &a.

Is there a way to do this with anonymous/unnamed intermediary structures, thinking an imaginary syntax something like

mytype b = {
    .next = &((mytype)={
        .next = NULL,
        .data = "a",
        }),
    .data = "b",
};

so I can build up the linked-list without naming each intermediary instance?

reddit.com
u/gumnos — 3 hours ago

How do you understand bitwising tricks

Im not Talking about basic operations, setting flags or bitshifting.
I speak about the tricks operations involving bitmasks and stuff.
I just can’t get how people get familiar with it.
I guess there is no magic way to understand, I just have to keep studying it, but do you guys have any resource or mental tips that can make me more familiar with these ?
Thank you

reddit.com
u/starya2K — 18 hours ago

How does explicit conversion work with assignment operators

I am studying c, I was messing around trying to figure out how explicit conversion works with assignment operators and came up with this:

#include <stdio.h>

int main()

{

int num1 = 5;

int num2 = 2;

float sum1 = num1 / num2;

float sum2 = (float) num1 / num2;

int sum3 = 5;

sum3 /= 2;

float sum4 = 5;

sum4 /= 2;

printf("sum1: %.2f\nsum2: %.2f\nsum3: %.2f\nsum4: %.2f", sum1, sum2, sum3, sum4);

return 0;

}

OUTPUT:

sum1: 2.00

sum2: 2.50

sum3: 2.50

sum4: 2.00

it seems sum3 converts to float automatically without explicit conversion when using assignment operators, but what confuses me is how sum4 manages to be 2 when its only difference was that it was declared as a float which if anything should make it behave better than sum3, is it something to do with the format specifier being wrong for sum3?

reddit.com
u/Guilty-Tomorrow-6134 — 16 hours ago

Can we write a generic byte-swap function for any struct in C?

Hello, I am not a native speaker so please forgive my language level.

Today I was working on my packet analyzer project. I was refactoring the code and I realized something: there are a lot of functions just to swap the byte order for every header (struct).

So I have a question: Can I build a function/program in C that can automatically swap the byte order of every field in any struct?

thank you all and this my project link : vex-packet-analyzer

u/E-Vex — 19 hours ago
▲ 0 r/C_Programming+1 crossposts

I need to learn c with memory and along with assembly mastering the memory...help with best yt channel...

currently learning c lang but i need to know more about the memory with assembly help me with thiss....

reddit.com
u/Mean_Parsnip_3007 — 20 hours ago

Why C is a simple language?

when I put the exact same question on google I only get things like "Is C worth in 202n?" or "Why you should learn C?".

C is simple compared with other languages such as Python, JS, Ruby etc. because of it's library variety? I mean, C doesn't have a 'pip' or 'npm'.

It's a really elementary question (maybe). Thank you C wizards!

reddit.com
u/rias_dx — 1 day ago

gitool: A Git cli tool written in C

Hi everyone,

I'm a CS student (Malaysian Chinese) currently learning C. I apologize if my grammar is wrong, my enligsh is really really bad.

I just finished reading C Programming Language: A Modern Approach (it took me about 2 months because I could only read this book during my semester break). I believe that the best way to truly learn any programming language is start building something real. To practice what I learned, I built gitool. Gitool is a command line interface tool to help you control your github repository like update file or delete directory.

Why did I build this?

  1. To practice C: Moving from textbook exercises to a project that can be helpful to people.
  2. I lowkey hate how Git handles things: As a Linux user, it always annoyed me how Git insists on creating .git directories everywhere and bloating my home directory with .gitconfig, especially when all I want to do is upload a single, specific file. (Honestly, I still don't fully get how everyone manages their dotfiles. Do you really git add your entire config directory just for one file or just create a lot of symbolic link ? I dont know, maybe I am a idiot).
  3. Is this tool already exists? I honestly don't know if this project even makes sense or if a much better alternative already exists out there. But hey, I really learn a lot than just reading.

A question for the community: Do you think we still need to learn code in future? I quite afraid get cooked by AI as a CS student.

Please roast my code! You don't have to help me, but I would really appreciate it if you could take a look at my repo. I'm posting this purely to level up my C skills and want to hear how you all think about this tool.

The development flows : gitool.c -> option.c -> command.c -> logger.c -> api.c -> list/upload/download/delete.c

GitHub Link: github/gitool

Thanks for your time, and looking forward to your roasts/feedback!

github.com

Built a lightweight Integer Overflow Detector in C. Need some brutal code review!

Hi everyone,

I've recently built a lightweight tool in C to detect and mitigate Integer Overflow (CWE-190) risks.

I wanted to make something practical for secure coding practices, so I implemented safe overflow checks using `INT_MAX`, `INT_MIN`, etc.

I've also documented how to compile and run it in the README. I would deeply appreciate any code reviews, edge-case checks, or feedback on how to improve the logic!

Here is the repository: https://github.com/gimgimdongjun79-lab/Integer-Overflow-Detector

Thanks in advance!

u/amondb — 1 day ago

any way to ensure that the heap always starts at lower order memory addresses?

hey all! I was just wondering if there was something like a compiler flag I could use when compiling to ensure that the heap always starts low and grows up in virtual memory.

reddit.com
u/True_Efficiency7329 — 2 days ago

What exercise you ever done was most interesting and fun for you?

Hi, It's few weeks I started to read C Programming: A Modern Approach from KN King and the exercises and mini projects are really good and fun, so I just wondering, what is your favourite exercise you still remember? (From books, classes, and other)

reddit.com
u/Aware-Mirror4994 — 2 days ago

Is this a good way of implementing an optional command line argument?

I'm very new to C so this might be an obvious problem to solve, but this is my way of checking for an optional command line argument, and changing mode based on that. Is this a safe solution?

int mode = 0; // default mode 0: relative pathing; 1 is exact pathing

int force = 0; // default force 0: dont overwrite; 1 to force writing

if (argv[1] == NULL || argv[2] == NULL) {

printf("mv: expected 2 arguments, \"mv [source] [dest]\"");

return 1;

}

if (strcmp(argv[1], "-f") == 0) {

char ch;

printf("force overwrite? (y/N): ");

fflush(stdout);

ch = getchar();

if (ch == 'y' || ch == 'Y') {

force = 1;

} else {

return 1;

}

}

if (1) {

printf("mode: %i\n", mode);

printf("force: %i\n", force);

printf("argc: %i\n", argc);

for (size_t i = 0; argv[i]; i++) {

printf("%s\n", argv[i]);

}

}

reddit.com
u/Specialist-Signal598 — 2 days ago

How to loop for wrong input

Just new to C and I'm trying to make a basic calculator. I'm trying to figure out how to make a loop such that the program will run after failing due to incorrect user input. So far, this is what I came up with, and I just want to know how I can get the program to actually run the operations when entering a correct sign after getting a "try again" message.

#include &lt;stdio.h&gt;

float addition(float num1, float num2)
{
return num1 + num2;
}

float subtraction(float num1, float num2)
{
return num1 - num2;
}

float multiplication(float num1, float num2)
{
return num1 * num2;
}

float division(float num1, float num2)
{
return num1 / num2;
}

int main()
{
float firstNum, secondNum;
char operationSign;
float answer;

printf("Basic Calculator\n\n");

printf("Enter the first number: ");
scanf("%f", &amp;firstNum);

printf("Enter the second number: ");
scanf("%f", &amp;secondNum);

printf("Enter the operation symbol to be used:\n");
printf("Addition:                            +\n");
printf("Subtraction:                         -\n");
printf("Multiplication:                      *\n");
printf("Division:                            /\n");
scanf(" %c", &amp;operationSign);

switch (operationSign)
{
case ('+'):
answer = addition(firstNum, secondNum);
printf("Answer: %f", answer);
break;

case ('-'):
answer = subtraction(firstNum, secondNum);
printf("Answer: %f", answer);
break;

case ('*'):
answer = multiplication(firstNum, secondNum);
printf("Answer: %f", answer);
break;

case ('/'):
answer = division(firstNum, secondNum);
printf("Answer: %f", answer);
break;

default:
printf("Invalid input. Please enter the correct symbol.");
scanf(" %c", &amp;operationSign);
}

return 0;
}
reddit.com
u/erojerisiz — 2 days ago
▲ 9 r/C_Programming+3 crossposts

My first C and raylib project

Coming from working in python and rust, this was filled with various emotions. Some good, some bad (build system).

I had made a rust TUI for my car diagnositcs. I've now replaced that with a GUI built with raylib and C.

The project itself is not too complex. I liked that I had a good enough idea about where my variables exist.

Other things I found interesting:

- manually lock and unlock mutexes rather than having them "wrapped" like rust. I believe there are ways to automate with attributes but I haven't learned that yet

- static vars because no OOP. particularly useful for storing animation state

- build system. I had a rough experience with cmake but got it to work. I want to build everything manually to learn how exactly its all being put together.

- side note: inspired confidence to dive into buildoot and optimize my pi image. Now boots 7s faster than my previous regular image process and manual flows.

Since I like driving manuals and learning about efficiency and whatnot, learning C was (still stressful) but rewarding. My previous project was a rust TUI, and now its "deoxidized" to this C project. Roller coaster ride.

youtu.be
u/f2se — 2 days ago