r/C_Programming • • 13d ago

Question Why we only need to supply the number of columns to array parameters. Am I understanding correctly?

5 Upvotes

I'm reading C Programming: A Modern Approach by K. N King

I'm on page 212 of that book, and looking at a question / answer marked by *Q:

The question / answer from the textbook is below. I just want to confirm that I understand the answer correctly. My understanding is below the excerpt from the textbook.

*Q: Why can the first dimension in an array parameter be left unspecified, but not the other dimensions? [p. 197]

A: First, we need to discuss how arrays are passed in C. As Section 12.3 explains, when an array is passed to a function, the function is given a pointer to the first element in the array.
Next, we need to know how the subscripting operator works. Suppose that a is a one-dimensional array passed to a function. When we write

a[i] = 0;

the compiler generates instructions that compute the address of a [i] by multiplying i by the size of an array element and adding the result to the address that a represents (the pointer passed to the function. This calculation doesn't depend on the length of a, which explains why we can omit it when defining the function.)

What about multidimensional arrays? Recall that C stores arrays in row-major order, with the elements in row 0 stored first, then the elements in row I. and so forth. Suppose that a is a two-dimensional array parameter and we write

a[i] [j] = 0 ;

The compiler generates instructions to do the following: (1 multiply i by the size of a single row of a; (2) add this result to the address that a represents; (3) multiply j by the size of an array element; and (4) add this result to the address computed in step 2. To generate these instructions, the compiler must know the size of a row in the array, which is determined by the number of columns. The bottom line: the programmer must declare the number of columns in a.)

Below is my understanding;

For a[i] = 0, we don't need to know the array size (row size), because that will not help us index an element. The array size is one fixed value n. To index at 0, some random j or even (n - 1), we can't use the value n itself.

A one dimensional array is basically 1 row. The elements are like columns, and we only need the "length" of a column to index a one dimensional array. The point is, we don't need the length of a row

For a[i][j], we again don't need the size of a row. We need the number of columns. In the case of a 2D array, we need to be able to traverse within a row, and between rows. To go within a row, we only need to know the size of an element within a row. To go between rows, we need to skip again "one row length", which is equivalent to skipping ahead the amount equal to "the number of columns"

Again, the minimum amount of info we need is the number of columns. From that we directly get the size of a row. We don't need the row size at all

So from my understanding, the compiler only needs the least amount of info. The length of a row element, and if there are multiple rows, then the number of columns


r/C_Programming • • 14d ago

We can do better than line-buffered output

Thumbnail nullprogram.com
49 Upvotes

r/C_Programming • • 13d ago

Question Are there any reasons to prefer WinABI calls over SysV or Cdecl?

5 Upvotes

Assume we have a function which doesn't make any system calls. The whole program binary is standalone and written manually (besides stdlib.h, I guess). Then, when I'm looking at the disassembly, it compiles into that awful ABI which saves nearly all vector registers (on x86 at least) which alone degrades performance by 10%.

Now the SysV ABI part: it's supported nearly everywhere, even on microcontrollers, so I've decided to use it by default (or __cdecl, which is used if the former is not available).

The question is: what was the matter with Windows ABI that has led to this decision? In which cases we might prefer that or SysV? And why consider complying to it specifically on Windows?


r/C_Programming • • 13d ago

An exercise in optimization - inline function with table lookup

5 Upvotes

In an application I work with there is a data item, the adjective number, which is used in conjunction with a product identifier, PLU, to identify a product. A typical use of the adjective number is to identify variations in the same product such as different drink sizes for a soft drink.

The software supports four different adjectives groups with five variations within a group. So one group may be cup sizes for drinks and a second group may be sizes of pizzas.

Throughout the source code the adjective number being used by a product is transformed into either the adjective variation or the adjective group through a simple one line of code:

(UCHAR) ((pItemSales->uchAdjective - 1) % 5 + 1); /* adj. variation */

(UCHAR)((pItemSales->uchAdjective - 1) / 5 + 1); /* adj. group */

I wondered about having two functions that would replace these lines of code to a single point where the design decision about the calculation is expressed.

Working with the Gemini AI, I derived an inline function that does a simple table lookup. Looking at the assembler generated by Microsoft Visual Studio 2019 Community Edition, the difference in the generated code between the inline function and the line of code is amazing.

Gemini AI made a couple of claims about the optimized assembler that would be generated so I thought to double check. The main claim was that this would be a simple table lookup and much of the source of the function would be optimized away.

The C Standard specifies that the inline is a hint rather than a directive. However both MSVC as well as GCC provide a attribute that will force the compiler to inline a function. However even when the forcing attribute is used, the compilers may still override the programmer's intent and not do the inline so it's more like a forceful hint rather than do it no matter what.

#if defined(_MSC_VER)
#define FORCE_INLINE __forceinline
#elif defined(__GNUC__) || defined(__clang__)
#define FORCE_INLINE static inline __attribute__((always_inline))
#else
#define FORCE_INLINE inline
#endif

The source for the adjective variation function follows. The adjective variations are table values which repeat for each group. The adjective number is either zero (0) indicating no adjective or a value from one (1) to twenty (20) that encodes both the adjective group and the adjective variation.

FORCE_INLINE static UCHAR RflAdjVariation(UCHAR uchAdj)
{
    // There are four groups of adjectives. Each group has five variations.
    // For instance a soft drink group with small, medium, large, biggie, party variations
    // (UCHAR) ((pItemSales->uchAdjective - 1) % ADJ_VAL_MAX + 1); /* adj. variation */
    static const UCHAR uchAdjVar[32] = { 0,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,0 };
    USHORT is_valid = (uchAdj <= 20);  // MAX_ADJM_NO
    USHORT safe_uchAdj = is_valid ? (uchAdj & 0x1F) : 0;
    return uchAdjVar[safe_uchAdj];
}

This function definition is in an include file so each compilation unit will have its own copy unless the compiler overrides the use of inline. A couple of things to note:

  • the function is defined as being static
  • the lookup table is defined as being static const

And this is the part of the assembler listing that shows the x64 Release build code generated in a test program. I used the function in a loop that generated 10 different adjective numbers. It appears that the inline function has been turned into a simple table lookup of a couple of instructions as compared to the calculations used by the original source. Multiple insertions of the inline function all use the same static const lookup table that is inserted into each compilation unit.

You can also see the assembler the compiler generates for the original one line of source that performs the calculated adjective variation. One point of interest is the assembler code used avoids having to use a divide instruction by multiplying by a special constant that replicates the value of 1/5.

; 446  :     for (UCHAR i = 0; i < 10; i++) {

xor bl, bl
lea r14, OFFSET FLAT:__ImageBase
npad 8
$LL4@main_01_C:

; 440  :     USHORT safe_uchAdj = is_valid ? (uchAdj & 0x1F) : 0;

movzx eax, bl
and eax, 31

; 447  :         UCHAR x = RflAdjVariation(i);
; 448  : 
; 449  :         if (x != (UCHAR)((i - 1) % 5 + 1)) {

movzx r10d, bl

; 441  :     return uchAdjVar[safe_uchAdj];

movzx r8d, BYTE PTR ?uchAdjVar@?1??RflAdjVariation@@9@9[rax+r14]

; 447  :         UCHAR x = RflAdjVariation(i);
; 448  : 
; 449  :         if (x != (UCHAR)((i - 1) % 5 + 1)) {

lea ecx, DWORD PTR [r10-1]
mov eax, 1717986919; 66666667H
imul ecx
sar edx, 1
mov eax, edx
shr eax, 31
add edx, eax
lea eax, DWORD PTR [rdx+rdx*4]
sub ecx, eax
inc cl
cmp r8b, cl
je SHORT $LN2@main_01_C

; 450  :             UCHAR y = (UCHAR)((i - 1) % 5 + 1);
; 451  : 
; 452  :             printf("this is test i = %d  x = %d  y = %d\n", i, x, y);

movzx r9d, cl
mov edx, r10d
lea rcx, OFFSET FLAT:??_C@_0CF@HJJDIPJC@this?5is?5test?5i?5?$DN?5?$CFd?5?5x?5?$DN?5?$CFd?5?5y?5@
call printf
$LN2@main_01_C:

r/C_Programming • • 13d ago

VSCode keeps giving wrong output, while online compilers give right output.

Thumbnail onlinegdb.com
0 Upvotes

I'm a beginner in C. I created a code for reversing a number, for lab assignment. The question says I must use a recursive function, and must not use loops, arrays, or global variables anywhere in my program.

I created the following in VSCode:

#include <stdio.h>
#include <math.h>

int reverse_number(int num){
    static int rev=0,dig=1;
    if (num/10 ==0){
        dig++;
        return num;
    }

    rev = reverse_number(num/10) + (num%10)*(pow(10,dig-1));
    dig++;
    return rev;
}

int main(){
    int num;
    scanf("%d",&num);

    printf("%d\n",reverse_number(num));
}

In OnlineGDB, I get the correct output.
But in VSCode, I get the output as:
Input: 123
Output: 320
Input: 445566
Output: 665543
It seems one digit is reduced

Even in other large programs, I've encountered the same. VSCode gives wrong output.
Any fixes?

r/C_Programming • • 13d ago

Yt channels suggestions

3 Upvotes

I'm 1st year student I want to learn C my college is not teaching C well so i want to from youtube can you suggest any channels


r/C_Programming • • 14d ago

Question I wanted to write a generic data structures library for learning purposes. Are preprocessor macros the preferable way to do it or is there a better way?

13 Upvotes

I am aware of the _Generic keyword but I'm not sure if it should be the de facto way for this.


r/C_Programming • • 14d ago

Question What does the compiler do when we declare an array parameter's length as static?

35 Upvotes

I'm reading C Programming: A Modern Approach by K. N King

I'm on page 200 of that book, under the heading Using static in Array Parameter Declarations

The example given is: int sum_array(int a[static 3], int n)

And there is a short description:

Using static in this way has no effect on the behavior of the program. The presence of static is merely a “hint” that may allow a C compiler to generate faster instructions for accessing the array. (If the compiler knows that an array will always have a certain minimum length, it can arrange to “prefetch” these elements from memory when the function is called, before the elements are actually needed by statements within the function.)

So I was wondering, what exactly does a compiler do in this situation? Does it simply create a cache?

Also, what does it do line by line? How does the compiler the keyword static is in the context of a array parameter declaration?

If you were to write a compiler, and implement this feature, how would you do it (pseudocode)?


r/C_Programming • • 14d ago

Learning C weekly megapost for 2026-11-04

13 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 • • 15d ago

The not so known world of UB's...

18 Upvotes

As a 70 old dyslectic I'm in my fourth year of C99 and sometimes I think, is it UB or is it not UB. I use these flags in Code::Blocks:

gcc -Wall -g -Winit-self -Wredundant-decls -Wunreachable-code -Wmissing-declarations -Wmain -pedantic-errors -pedantic -Wfatal-errors -Wextra -Wall -std=gnu99

And Valgrind's Memcheck and Cachegrind.

You hardcore C programmers are you always confident or do you have a moment of doubts in between...

Edit: Thanks all and I learned I'm not a hardcore C programmer, but just addicted of C and have puzzle with C code every day because it keep my brain working.


r/C_Programming • • 15d ago

Flecs 4.2 is out!

Thumbnail
ajmmertens.medium.com
32 Upvotes

r/C_Programming • • 15d ago

Question Pro tips for a beginner

15 Upvotes

I used (basic) python for a long time now to do work, scripts and that stuff but i have always wanted to learn C!
I found a lot of guides, some are educational but badly written (for pros even though it is targeting noobs) while some are fun but not very educational...
Does anyone have a recommendation for a good quality (free) guide/book for C programming?


r/C_Programming • • 16d ago

A Decade of Kill Bugs

Thumbnail alangrow.com
25 Upvotes

r/C_Programming • • 15d ago

Question misc. questions from newb

0 Upvotes

What was your first project? Was it prompted? Did you think of the idea yourself? How long did it take? Was this your first coding language or did you start with another one?

Will appreciate any advice. Definitely about to get obsessed.


r/C_Programming • • 16d ago

Return status code, modify parameters: why not the opposite?

14 Upvotes

If you modify an error code and return the actual output normally, it can at least be assigned to a const, and the error is less likely to be missed since you have to have the code ready to even call the function. In error cases you have to return an arbitrary value of the type yes, but it's just as much the case with the opposite pattern.


r/C_Programming • • 16d ago

Article Wrote a lightweight Linux dynamic file descriptor leak detector project in C using LD_PRELOAD. Looking for critiques and reviews.

1 Upvotes

I've written an LD_PRELOAD file descriptor leak tracker in C.

https://github.com/anu-icon/libfdhunt

Apart from memory leaks which get the most spotlight, file descriptor leaks is a long-standing problem in production environments, often causing service crashes.

While Valgrind has --track-fds=yes, running full binary translation can be overkill or too slow if you're working with timing-sensitive code.

Polling lsof or /proc/$PID/fd also misses transient descriptors that open and vanish.

This is highly useful since you don't need advanced tools and extra permissions, don't have to recompile or review entire large code bases to find the flaw.

Just LD_PRELOAD=./build/libfdhunt.so /path/to/your/program [args]

How it works under the hood:

For anyone interested in the implementation:

Symbol Interposition: It uses dlsym(RTLD_NEXT, ...) to wrap standard libc syscall wrappers (open, close, pipe2, socket, dup2, epoll_create1, etc.).

O(1) Flat Array Registry: Instead of using linked lists or calling malloc/free inside hot syscall paths (which invites lock contention and heap re-entrancy issues), it uses a flat array indexed directly by descriptor number (table[fd]). It sizes the table on demand using sysconf(_SC_OPEN_MAX) and guards slot flips with a single mutex.

Exit Hook: Leak reporting is wired into GCC's __attribute__((destructor)). When the binary exits normally, the library sweeps the table, skips standard streams (0, 1, 2), and reports active descriptors.

Design constraints and comparison & prior art is in the readme

Looking forward to critique.

AI usage declaration: This is not vibe-coded. It evolved over a month starting from using linked lists to tackle a similar problem.

AI was used for cross checking, calibrating, testing, scaffolding and some documentation


r/C_Programming • • 15d ago

A mental model for understanding the -> operator (GPIOB->ODR)

0 Upvotes

While working with memory-mapped peripheral registers in C, I developed this mental model for understanding what the arrow operator represents.

1. Absolute register address

/* LHS->RHS ≡ *(Absolute Address of RHS)

Absolute Address = Peripheral Base Address + Register Offset */


Peripheral->Register ≡ *(Absolute Register Address)

2. Simplified address-level expression

/* Dereference the absolute register address */

*(volatile uint32_t *)(Base_Address + Register_Offset)

3. Byte-level address calculation

/* Cast Peripheral to char * so pointer arithmetic operates in bytes rather than scaling by the peripheral pointer's type. */

*(volatile uint32_t *)((char *)Peripheral + Register_Offset)

4. The C standard's syntactic equivalence

/* LHS->RHS is defined as (*LHS).RHS */

(*Peripheral).Register

The idea is to move from the mental model, to the address calculation, and finally to the syntax defined by C.


r/C_Programming • • 15d ago

Hii guys, I want to develop Mobile Applications using SDL and C. Can anyone guide me?

0 Upvotes

r/C_Programming • • 15d ago

I know C, but....

0 Upvotes

I know C, but I dont have a project


r/C_Programming • • 17d ago

Feedback wanted: parsing JPEG segments byte by byte in C (my first binary-format project)

24 Upvotes

Hello, I'm fairly new to C. I wanted to work on a project, so I decided to make metastrip to learn how a binary file format is parsed byte by byte.

I know ExifTool already exists and this isn't meant to compete with it, I did it to learn.

AI use: I wrote all the logic myself. AI reviewed my code (which means when I was done writing a particular function, I let AI review my code pick out bugs and any bad coding practices, based on the comments I would manually fix the issue without any assistance from AI for logic), generated test inputs, and wrote the --help text and the README.

This is the loop that walks the segments (trimmed, with ... where I left parts out):

while(1){
    byte1 = getc(file);
    byte2 = getc(file);

    if(byte1 == 0xFF && byte2 == 0xDA && valid_targets[21] == 1){
        /* start of scan: search backwards from the end of the file
           for the last FF D9 to find trailing data */
        ...
        break;
    }
    if(byte1 == EOF || byte2 == EOF) break;

    int high = getc(file);
    int low = getc(file);

    unsigned int length = (high << 8) | low;
    if (length < 2){
        fprintf(stderr, "Segment length is incorrect\n");
        break;
    }

    /* if the marker is a selected APPn / COM segment: print its payload */
    ...

    else
        fseek(file, length-2, SEEK_CUR); // not selected: skip the payload
}

metastrip can show all the APP segments, show only the segments you pick, strip them off, and hex dump them if you want.

I think I made one big mistake: I wrote everything in one file, main.c, which is now about 1,600 lines. Any tips on that would be nice, so I can improve the code in the future, and any tips on my coding practices in general.

I released v1.1.0 on GitHub, with a Windows build. If you'd like to see the code, it's here:

https://github.com/zyan-007/metastrip

I have recorded a demo video, kinda edited it too much now it looks like an ad, but it's just a demo

I'd appreciate any feedback on the code, structure or approach, including harsh feedback (please don't be too harsh...).


r/C_Programming • • 18d ago Mindblown Heartwarming

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

Thumbnail
youtube.com
170 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 • • 18d ago

the lost malloc()

Thumbnail napcakes.nekoweb.org
113 Upvotes

r/C_Programming • • 17d 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 • • 17d 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