/r/cprogramming

Photograph via snooOG

A Subreddit dedicated to the C programming language. Everything related to C is welcome here.

A subReddit for all things C

C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions. It has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computer architectures that range from supercomputers to PLCs and embedded systems. Wikipedia

Paradigm

Imperative (procedural), structured

Designed by

Dennis Ritchie

Developer

Dennis Ritchie & Bell Labs (creators);

ANSI X3J11 (ANSI C);

ISO/IEC JTC1/SC22/WG14 (ISO C)

First appeared

1972 (48 years ago)

Stable release

C18 / June 2018 (2 years ago)

Typing discipline

Static, weak, manifest, nominal

OS

Cross-platform

Filename extensions

.c for sources

.h for headers

Resources


C++ is not C (but C can be C++)

For C++ go to :


Other Resources

/r/cprogramming

33,533 Subscribers

1

Solutions of C programming: a modern approach by K.N King

Can anyone provide me the solutions to the book mentioned above

0 Comments
2024/11/21
07:52 UTC

0

Pointer of Strings on the Stack

Hi guys,

when we declare a string literal like this, char *c = "test..."; it's being allpcated on the stack & the compiler can do this as it knows the length of the string.

but oddly, i can do this:

char c1[25] = "strings one";
char c2[25] = "string two";
char *c[25];
c[0] = c1;
c[1] = c2;

and things will appear to be working just fine. i am thinking that this is supposed to be undefined behavior because i had not given the compiler concrete information about the latter char pointer - how can the compiler assume the pointer has it's 1st and 2nd slots properly allocated?

and on that note, what's the best way to get a string container going without malloc - i'm currently having to set the container length to a pre-determined max number...

thanks

5 Comments
2024/11/21
01:57 UTC

0

Help understanding why one of my functions is not working

I made a program to store contacts data in a structure and I want one of the functions to delete a contact from the list and free up the memory of it but it is giving me an error each time and I can not figure out why. My addContact and displayContacts functions work correctly but my code hits a breakpoint at my scanf in my deleteContact function. Any suggestions?

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_CONTACT_NAME 50

#define MAX_CONTACT_PHONE 20

#define MAX_CONTACT_EMAIL 50

typedef struct contact {

char name\[MAX\_CONTACT\_NAME\];

char phone\[MAX\_CONTACT\_PHONE\];

char email\[MAX\_CONTACT\_EMAIL\];

}contact;

void addContact(struct contact *contacts, int *numOfContacts) {

printf("What is the name of the contact?\\n");

scanf\_s(" ");

gets(&contacts\[\*numOfContacts\].name);

printf("What is the phone number?\\n");

scanf\_s(" ");

gets(&contacts\[\*numOfContacts\].phone);

printf("What is the email?\\n");

scanf\_s(" ");

gets(&contacts\[\*numOfContacts\].email);

}

void deleteContact(struct contact *contacts, int *numOfContacts) {

char userInput\[50\];

int invalidChecker = 0;



printf("What contact would you like to delete?\\n");

scanf\_s("%s", &userInput);

for (int i = 0; i < \*numOfContacts; i++) {

	if (userInput == &contacts\[i\].name) {

		\*contacts\[i\].name = NULL;

		\*contacts\[i\].phone = NULL;

		\*contacts\[i\].email = NULL;

		free(&contacts\[i\]);

		invalidChecker++;

	}

}

if (invalidChecker == 0) {

	printf("Invalid name\\n\\n");

}

else if (invalidChecker == 1) {

	printf("Contact deleted\\n");

}

}

void displayContacts(struct contact* contacts, int* numOfContacts) {

for (int i = 0; i <= \*numOfContacts; i++) {

	int count = i + 1;

	printf("\\nContact #%d\\n", count);

	puts(&contacts\[i\].name);

	puts(&contacts\[i\].phone);

	puts(&contacts\[i\].email);

}

}

int main() {

int input, numOfContacts = 0;

contact \*contacts = (contact\*)realloc(numOfContacts, sizeof(int));

do {

	printf("What would you like to do?\\n");

	printf("1. Add contact\\n");

	printf("2. Delete contact\\n");

	printf("3. Display all contacts\\n");

	printf("0. Exit\\n");

	printf("What is your choice: ");

	scanf\_s("%d", &input);

	switch (input) {

	case 1:

		addContact(contacts, &numOfContacts);

		break;

	case 2:

		deleteContact(contacts, &numOfContacts);

		break;

	case 3:

		displayContacts(contacts, &numOfContacts);

		break;

	default:

		printf("Invalid input\\n");

		break;

	}

} while (input != 0);



return 0;

}

4 Comments
2024/11/20
19:27 UTC

0

why?i think it's right.

#include <stdio.h>
void w(int *****d) {
int ******f=&d;
    printf("%d",******f);
}
void b(int ***t) {
    int ****d=&t;
    printf("%d",****d);//if the t is changed to w there will have an error,but i don't think it is logically wrong.
    //called object type 'int ***' is not a function or function pointer
   // w(&d);
  //  ~^
    w(&d);
}
void a(int *q){
    int **c=&q;
    printf("%d",**c);
    b(&c);
}
int main(){
    int x=10;
   a(&x);
}
15 Comments
2024/11/20
16:37 UTC

0

Help with Visual studio

hey fellow coders, a beginner here....trying to setup visual studio....but then I end up with this in my terminal

[Running] cd "c:\Users\viky4\OneDrive\Desktop\Code files\" && gcc hi.c -o hi && "c:\Users\viky4\OneDrive\Desktop\Code files\"hi
C:/ProgramData/mingw64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/ProgramData/mingw64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.2.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crtexewin.o):crtexewin.c:(.text.startup+0xbd): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

[Done] exited with code=1 in 0.574 seconds

A lil help would be appreciated

3 Comments
2024/11/20
08:40 UTC

0

Advices

Hello, I’d like to ask for some advice regarding an exam. There’s really a lot of material, and I’d need some basics to put on a cheat sheet or to review. We’ll need to write a program, but so far, I’ve been relying on documentation when creating programs, and now it has to be written from memory… Thank you for any advice, and there’s no need to vent your frustration here. I know it’s not an easy topic.

6 Comments
2024/11/19
12:30 UTC

33

I never understand why everyone add all #include in source files instead than header files?

I always think its more simple to add all include in thismodule.h and in thismodule.c you just need to add "thismodule.h".

21 Comments
2024/11/18
21:22 UTC

10

Using qsort and and search to implement a ordered map on realtime embedded software

As part of my current project I was asked to implement a ordered map (similar std::map in C++) but only using C and the standard C library for a embedded software I came across qsort and bsearch which were supported by platform and implement such a database with these functions seems trivial with these functions. However according to Misra standard qsort and bsearch seems to be prohibited. Can somebody explain why and more importantly why is it prohibited even if I know my implementation is type safe

8 Comments
2024/11/18
18:17 UTC

0

What am I doing wrong here?

The code works as intended for normal matrices but starts giving garbage values when all the entries are 1

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

void main()

{

int i=1,j=1,rw_a=1,col_a=1;//initalizing all variables 

printf("number of rows in matrix A: ");

scanf("%d",&rw_a);
printf("number of coloumns in matrix A: ");

scanf("%d",&col_a);
float mat_a[rw_a][col_a];

printf("enter the values of matrix A\n")//inputing values in matrix A
for(i=0;i<rw_a;i++)
{
    for(j=0;j<col_a;j++) 
    {
        scanf("%f",&mat_a[i][j]);
    }
}

for(i=0;i<rw_a;i++) //for converting the matrix to echlon form
{
    for(int k=i+1;k<rw_a;k++)
    {
        for(j=0;j<col_a;j++) 
        {
          mat_a[k][j]=mat_a[k][j]-(mat_a[i][j]*mat_a[k][j])/mat_a[i][i];
        }
    }
}

printf("matrix A=\n");//Displaying values of matrix A
for(i=0;i<rw_a;i++)
{
    printf("[");
    for(j=0;j<col_a;j++) 
    {
        printf(" %f ",mat_a[i][j]);
    }
    printf("]\n");
}
exit(0);

}

4 Comments
2024/11/18
15:06 UTC

2

Creating another "language" with macros

I was asking myself if someone created a "language" with C, by only using macros, like, not only replacing simple words, but there are some dark magic that can be made using macros, like replacing only parts of the fields, adding optional parts, etc.

I also was thinking if someone had made like an "O.O. C" with only macros or made C a more functional language too, with some wizardry

15 Comments
2024/11/18
09:16 UTC

4

When to use a macro

I have a case where I'll have to check multiple variables for negative values and clip them.

The easiest way I see is by using a macro and apply that to all the variables. Something like this :

#define SOME_MACRO(VAL) ( (VAL <0) ? 0 : VAL )

And there's the classic if else condition which could be applied to each variable.

if ( VAL < 0){ VAL = 0; } else { /* do nothing */}

Which, obviously needs more code to be written to achieve the same output.

Putting the obvious aside,

I'd like to know which of these methods is better since I'm running this on a microcontroller. If somebody can explain what happens behind the scenes with regards to memory etc, that would be great.

11 Comments
2024/11/18
07:48 UTC

5

c-web-modules: "Kernel" Modules for the Web (proof of concept)

I’ve been working on my hobby project inspired by kernel modules and AWS Lambda. The idea is pretty simple: write some raw C code, upload it to a server, and it compiles and runs it at runtime. No precompilation, no restarts. :D

C isn’t usually the go-to for web dev (for good reasons), but here’s how I’ve tried to make it less painful:

• ⁠Slow Build Cycles: Upload code, and the server handles the rest—like "hot reloading," but in C. • ⁠Speed vs. Practicality: Great for scenarios where performance actually matters, like data-heavy or real-time stuff. • ⁠Memory Management: Modules are isolated, so crashes don’t take everything down. • ⁠Built-In Libraries: Comes with SQLite3, OpenSSL, and Jansson support to save you from reinventing the wheel.

It’s just a proof of concept, not production-ready (please don’t deploy it), but it’s fun to work on! Would love any feedback on it. It allows for some interesting possibilities, like being able to update WebSocket handlers at runtime without even closing the WebSocket connection.

GitHub c-web-modules

3 Comments
2024/11/17
15:10 UTC

27

Best textbooks/books for learning C

I’m trying to learn C. I have a bit of a background in Arduino but I want to get better at the language in general and get better at it for arduino

33 Comments
2024/11/16
16:09 UTC

40

Writing a simple kernel using C and asm

While looking through projects for C and other low-level stuff, I chanced upon a repo on GitHub called "Build your own x"

https://github.com/codecrafters-io/build-your-own-x

This is my version of writing a simple kernel using C and asm

https://medium.com/@sumant1122/write-your-small-kernel-17e4496d6d5f

4 Comments
2024/11/16
14:08 UTC

9

Is this the best way to check if a character is a letter?

I wanted to write a compact expression to check if a character is a letter, and as of now I came up with this. How good is it? Can it be improved? Thanks for your time!

int is_letter(char c)
{
  return (c | 32) - 'a' < 26u;
}
28 Comments
2024/11/16
12:40 UTC

0

== and =

hi i want to ask i'm still confused what is the difference between == and = in C? T_T

6 Comments
2024/11/16
12:06 UTC

1

what am i doing wrong here

why is the value in the rows of the matrix not getting sorted?

#include<stdio.h>
int main(){
    int mat1[4][4], mat2[4][4], soln[4][4];
    int i,j;
    printf("number of matrix 1");
    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            scanf("%d", &mat1[i][j]);
        }
    }
    /*printf("number of matrix 2");
    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            scanf("%d", &mat2[i][j]);
        }
    }

    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            soln[i][j]=mat1[i][j]-mat2[i][j];
        }
    }
     printf("solution matrix is");
    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            printf("%d ", soln[i][j]);
        }
        printf("\n");
    }
    */

    printf("original matrix is");
    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            printf("%d ", mat1[i][j]);
        }
        printf("\n");
    }

    int rows;
    
    for(rows=0; rows<4; rows++){
    for(i=0; i<4; i++){
        //int min=mat1[rows][i];
        for(j=i+1; j<4; j++){
            int min=mat1[rows][j];
            if(min> mat1[rows][j]){
                int temp=mat1[rows][j];
                mat1[rows][j]=min;
                min=temp;
            }
        }
    }
}
    printf("sorted matrix is");
    for(i=0; i<4; i++){
        for(j=0; j<4; j++){
            printf("%d ", mat1[i][j]);
        }
        printf("\n");
    }

    return 0;
}
8 Comments
2024/11/15
18:00 UTC

4

UB? but it works

Yesterday I was doing os exercises for college, and I found this function:

int factorial(int n){ if (n > 1) return n * factorial(n - 1); }

As it has no return if n <= 1 it reaches the }, and I found in ieee standard C that the returning value is not defined. Also I cant found any info in gnu C manuals. I want to know why the function return the value in "n". I think that compiler would share registers to store arguments and return value.

10 Comments
2024/11/15
09:27 UTC

7

Need a little help with my C project( I am a beginner )

I am just starting on making a 6502 CPU emulator(and I am new to emulation dev as well) using C and have a weird error like this even though I have included the header file in which the struct is declared.
src/instruction.h:91:10: error: unknown type name ‘cpu_6502_t’

91 | void TYA(cpu_6502_t* cpu_6502, struct instruction_t* selected_lookup);

It is a small project and I would appreciate if anyone could take a look at it and help. I would be absolutely great if you could suggest me ways in which I can improve my code.

Here is the github repo for the project if you wanna take a look.
https://github.com/AbhisekhBhandari/NES

Thanks!

5 Comments
2024/11/14
10:19 UTC

7

Interesting perspective of time complexity in bubble sort.

We generally accept the time complexity of bubble sort as O(n^2) no matter it is best or worst case.

But if the given array is already sorted in order and there is a variable that counts the time of switch, would the time complexity for the best case be O(n)? This approach is originally stated in book which name is "A book on C"

<Example code>

#include <stdio.h>

void bubble_sort(int list[], int n) {

int i, j, temp;

for(i = n - 1; i > 0; i--) {

int cnt = 0;

for(j = 0; j < i; j++) {

if(list[j] < list[j + 1]) {

temp = list[j];

list[j] = list[j + 1];

list[j + 1] = temp;

cnt++;

}

}

if(cnt == 0) break;

}

}

int main() {

int i;

int n = 5;

int list[5] = {7, 5, 4, 3, 1};

bubble_sort(list, n);

for(i = 0; i < n; i++) {

printf("%d\n", list[i]);

}

}

8 Comments
2024/11/14
06:18 UTC

2

small paint-like program

I created a small paint-like program in C to practice some programming skills. I used the SDL3 library to set up the window and access various graphic functions. The project involves extensive use of pointers, dynamic memory allocation with malloc, arrays, and other techniques I learned in the CS50x course.

Check out the code here: https://github.com/gleberphant/DRAW_PIXELS_SDL.git

2 Comments
2024/11/14
00:02 UTC

7

Array of Pointers best practices

Hi everyone,

I would like your opinion on the best practice for a C program design. Let's say I would like to have one array, and I want to use an if statement to either add or remove the last element of array based on a condition.

Here's a sample code:

char *array[] =    { "TEST",
                   "SCENARIO" };
char *array1[] =    { "TEST",
                   "SCENARIO",
                    "MODE" };
char **ptrTest;

if ( something here )
   ptrTest= array;
else
   ptrTest= array1;

In this example:

  1. I have two 2 arrays of pointers, array and array1.
  2. Based on a condition, I select either array or array1.

I wonder if this is the best practice. Is there a more efficient or cleaner way to handle this scenario, because if I had more arrays then I would have to use a copy for each array without the elements I want?

Thank you!

8 Comments
2024/11/13
19:14 UTC

9

Is it possible to write a hosted implementation of C that draws a pixel to the screen without including header files?

This is directly related to a previous question I posted either here or r/osdev.

After some researching, I have a better understanding of how C works... or do I?

I write this here to make sure what I understand doesn't contradict anybody else's knowledge. What I am trying to do is write a c file that talks to the screen and draws a pixel.

What does it mean to talk to the screen? Given my conditions of using no header file and having one C file do the job, it would probably writing to the framebuffer, which should have a series of addresses that C can modify, This can work in a Linux terminal by writing cat /dev/urandom > /dev/fb0 assuming right video permissions. But the framebuffer is provided by the kernel, a part of the OS that must be written with some kind of libraries.

I would guess that all the low-level,, OS-dependent stuff is written using the standard libraries. Those same standard libraries that are stdio.h, libgc.h, stdarg.h, stdlib.h, string.h, and much more...

Given my want to do this library-free, one might say I am looking for a "freestanding implementation" of C, or a C program written on an Arduino or any OS-less embedded system. While I do have an Arduino and I do have a working program that does more than just a pixel, it is for a different model of LCD than the one I have and I cannot figure out how the datasheet works and I don't think a semester of CS will be worth it - since I already am in a program which I wish not to name.

I heard that C cannot make syscalls. On the other hand, I heard otherwise. I am not sure which it is, so I am considering the usage of inline assembly.

Depending on the compiler, I could, for an example using gcc, write asm () and do assembly there. Additionally, one could compile a C program and LINK IT to an asm program, with maybe one more step I forgot about, which, in one way, does seem to follow my condition, but in another, kind of not sure... because you are linking a C to an asm, and it feels similar to linking a C to a bunch of H's.

Can C on its own make syscalls like asm can? Whatever the answer may be, I would need to rely on registers, which should be accounted for since I am on a Mint VM running on x86_64 architecture. How do I lay out the screen's addresses from the registers? And can I do this while on Mint tty or does the fact I am on an OS make the task impossible? I should know it isn't since I can make the kernel write to the framebuffer with a command. But I guess I am trying to work without a kernel?

I just found this link that explains kernels and bootloaders and "standalone" programs, which seems to be what I am wanting to do... while on Mint, much better than any other link or video I found: https://superuser.com/questions/1343849/would-an-executable-need-an-os-kernel-to-run

I wonder if I am making contradictory wishes by saying I want a standalone program while working on one that makes syscalls on Mint.

Hm... I mean, the link does say that you cannot at all, run such a program while an OS is booted - meaning I have to make an OS-less VM or work on my RISC Arduino... Can you just write a C (or C + asm) file that bypasses the kernel or what?

This is a reiteration of the same exact issue that I have published in multiple communities. What I tried doing differently here is showing that I kind of or kind of don't know what I'm talking about, and being precise about what I want to do, because people tend to say they don't know what I want, which is honestly confounding to me, so I hope this remedies that!

Am I getting all this right? If so, would it be possible to do what I set out to do?

79 Comments
2024/11/13
15:01 UTC

0

Is graphics.h for c or c++

I installed graphics.h in hope to use in my c project but when I tried to build the project this error message appeared:

/mingw/include/graphics.h:30:10: fatal error: sstream: No such file or directory

30 | #include <sstream> // Provides std::ostringstream

| ^~~~~~~~~

compilation terminated.

ninja: build stopped: subcommand failed.

thanks in advance for any help

4 Comments
2024/11/13
12:46 UTC

3

i++ vs ++i

What is the difference:

#include <stdio.h>

int main(void)

{

int A[5] = { 1, 2, 3, 4, 5 }, B[5];

// 1. Works -> B = { 1, 2, 3, 4, 5 }

// for (int i = 0; i < 5; B[i] = A[i], ++i) { ;; }

//2 . Doesn't work -> B = { x, 1, 2, 3, 4 }; -> x is some unknown value, sometimes is 0, sometimes negative...

for (int i = 0; i < 5; B[i] = A[i++]) { ;; }

printf("Array A: ");

for (int i = 0; i < 5; ++i)

printf("%d ", A[i]);

printf("\nArray B: ");

for (int i = 0; i < 5; ++i)

printf("%d ", B[i]);

return 0;

}

10 Comments
2024/11/13
08:29 UTC

3

TCP receive buffer

I prefer system over library calls for control, obviously, but even then, there are deeper levels.

I know with sockets, packets are handled at the kernel level, and recv reads from that buffer.

My question is, in C, is there a way to interrogate that TCP receive buffer, or, if it's memory mapped like open, can you get the pointer to that address?

My guess is no, because unlike open, it's owned by the system, not the process, but I'm just curious.

5 Comments
2024/11/11
20:47 UTC

2

What is the fastest sorting algorithm

12 Comments
2024/11/11
12:24 UTC

9

Creating a build system for C

Today I discover Poac, it's cool but it's cpp.

How difficult would it be to create one for C?

The same as cargo in Rust, but for C. With the ability to create a project, add dependencies and cross-compile with 3 words max (I'm obviously exaggerating, but you know what I mean.).

I'm clearly not a C expert, but I need a big project right now and I must admit I'm hesitant to give it a try.

20 Comments
2024/11/11
01:23 UTC

20

Why is C so lenient in this aspect?

This is actual code that can run without error or warnings. Why??

#include <stdio.h>

int main() {
    const auto char const p[:> = "Hello world!";
    <%
}
    puts(p);
    return 0;
    %>
15 Comments
2024/11/10
03:26 UTC

Back To Top