/r/C_Programming

Photograph via snooOG

The subreddit for the C programming language

Rules

  1. Format your code properly (4 leading spaces, correctly indented)
  2. Only C is on topic (not C++, C# or general programming)
  3. Do not post links as self posts
  4. No pictures of code

Filters

Click the following link to filter out the chosen topic

Resources

Other Subreddits on C

Other Subreddits of Interest

/r/C_Programming

177,027 Subscribers

1

Does a static/global variable get changed when multiple instances of program are run?

This question might be stupid, but I am genuinely curious. Let's say I have a static variable inside a function. According to my understanding, the static variable's lifetime is the program's lifetime. It is initialized only once(during the first function call), and every subsequent invocation of the function will modify its value (if the function has some operations modifying it). Now, let's say we have a static variable inside a function. We call the function every i seconds. And we have 2 instances of the program running. Will the execution of the second instance of the program affect the static variable running in the first program?
The same question for a global variable, which is present in a header file and made extern to be accessible across the project. The lifetime of a global variable, too, is throughout the program. Will it be affected similarly?

Example code 1:

/* File : example1.c */
#include <stdio.h>
#include <unistd.h>

void static_func() {
  static int x = 0;
  x++;
  printf("%s: Value of x : %d\n", __func__, x);
}

int main() {
  while(1) {
    static_func();
    sleep(1);
  }

  return 0;
}

Running the code:

$ clang example1.c -o example1
$ ./example1
# In a different terminal shell
$ ./example1

Example code 2:

/* File : example2.c */
#include <stdio.h>
#include <unistd.h>

extern int x;
x = 0;

void update_func() {
  x++;
  printf("%s: Value of x : %d\n", __func__, x);
}

int main() {
  while(1) {
    update_func();
    sleep(1);
  }

  return 0;
}

Running the code:

$ clang example2.c -o example2
$ ./example2
# In a different terminal shell
$ ./example2

I coded and ran a program similar to example 1, running two threads in the code. On running two instances of the code, I noticed that the variable count value started from 0 for both programs. But I would still like a clearer answer as to whether the variable will be affected or not and the reason for either.
Any help clarifying this is appreciated. Thank you!

9 Comments
2024/11/20
05:30 UTC

1

Can this code be made vectorizable?

can this code be made vectorizable?

   for(i=0;i<n-1;i++)
    {
      a[i+1] = b[i]+1;
      b[i+1] = f[i]+a[i];
    }

My goal is to adjust the code in a way that still outputs the same arrays, but is vectorizable and performs better single-threaded. I am using Clang to compile/vectorize this.

My attempt to adjust is below, and it vectorizes but it does not perform better. I have a feeling that I cannot vectorize this kind of formula because it always depends on a previous calculation. Since it needs to be single threaded unrolling the loop would not benefit it either correct?

    b[1] = f[0] + a[0] + 1;
    for(i=1;i<n-1;i++)
    {
      temp = b[i-1] + 1;
      b[i+1] = f[i] + temp;
      a[i] = temp;
    }
    a[n-1] = b[n-2] + 1;
6 Comments
2024/11/19
23:19 UTC

1

Requesting an Overview

Hello ladies and gentlemen, I would like your advice on how to tackle new concepts as a novice to C who would like to build a solid foundation, note that I'm following the 42 school course and am currently on the project "Get next line" and "ft_printf", in the first project "Libft" I tackled memory management, string manipulation, linked lists, and glimpses of file descriptors. I noticed that the theoretical parts take time to understand and sometimes make me feel overwhelmed if delve deeper into them by curiosity.
My question for you is how you have dealt with it, and what approach would you recommend?

0 Comments
2024/11/19
22:50 UTC

1

Function-like macro confusion

I'm running into a compiler error that has me scratching my head a bit.

typedef enum
{
    FOO_TYPE_ABLE = 0,
    FOO_TYPE_BAKER = 1,
    FOO_TYPE_CHARLIE = 2
} foo_param_type;

unsigned long foo(foo_param_type x);
unsigned long bar(void);

#define MY_FOO() ((uint32_t)(foo(FOO_TYPE_ABLE)))
#define MY_BAR() ((uint32_t)(bar()))

MY_BAR is an existing macro that has compiled and worked fine for quite a while now. I'm currently trying to get MY_FOO working, but when I try invoking the macro in my code, e.g. uint32_t current_foo = MY_FOO();, the compiler will return an error "expression preceding parentheses of apparent call must have (pointer-to-) function type".

Any idea why MY_FOO()would not be considered function-like?

UPDATE: Solved thanks to /u/developer-mike - https://www.reddit.com/r/C_Programming/comments/1gv90nu/functionlike_macro_confusion/ly03f6d/.

7 Comments
2024/11/19
21:50 UTC

1

Im having problems making a snake game in C on the console.

As you might be able to see my code kind of works except for a crucial part, which is the snake growing, everything else kind of works. Ive kind of managed to made a dynamic list for the position of each of the snake segments, each segment is a node containng the snakes position in te console and the next nodes memories location , i only control the head of the snake (last element of the list) and update every following segment subsecentially, in other words if the head is x=5 y=5 and in the next game tick it becomes x=6 y=5 then the previous segment of the snakes head will become x=5 y=5, following that pattern until you have updated every segment on the snake. I also have a buffer that follows the snakes tail and deletes its trail, its all made using ansi code. everything seems to logically work but i cant find the problem and ive been stuck on this for 2 days and dont know how to solve it at all, so any help will be appreciated! Also i dont know if my problem is in memory management or on any other department. And so here it is the defformed child if you want to try it yourself bear in mind that your console supports ansi code! In windows most consoles that i have tried support it if you exectue the game as an administrator, i am deeply sorry for my shitty code, i am still a novice:

#include <stdio.h>

#include <stdlib.h>

#include <windows.h>

#include <stdbool.h>

typedef struct snake

{

int x_pos;

int y_pos;

struct snake* next;

} snake;

int randomBetween(int min, int max);

void windowManagement(int wind_x, int wind_y, int wind_h, int wind_w);

void georginasCookies(snake** segmentPtr, int* x_food, int* y_food, int* snakesLength, int x_buffer, int y_buffer);

void addSegment(snake** segmentPtr, int x_pos, int y_pos);

void controls(snake* segment);

void drawSnake(snake* segmentPtr);

void updateSnake(snake* segment);

int main() {

//Starts random seed

srand(time(NULL));

//Manages console position and size

windowManagement(710, 290, 500, 500);

//Hides cursor

printf("\033[?25l");

//Creates a snake

snake* segmentPtr = NULL;

snake* segment = malloc(sizeof(snake));

if (segment == NULL)

{

printf("Theres no space in memory to run the game");

return 1;

}

//Declares the head of the snake

segment->x_pos = 1;

segment->y_pos = 1;

segment->next = NULL;

//We get a pointer to the head for later use

segmentPtr = segment;

//A position buffer that will go behind the snake changing its trail back into air

int x_buffer = 0;

int y_buffer = 0;

// Random food position

int x_food = 5;

int y_food = 5;

printf("\x1b[%d;%dHX", y_food, x_food);

int points = 0;

//Program is running nonstop unless the user hits the esc key

while (1)

{

printf("\x1b[%d;%dH ", segmentPtr->y_pos, segmentPtr->x_pos);

x_buffer = segmentPtr->x_pos;

y_buffer = segmentPtr->y_pos;

updateSnake(segment);

//Game controls

controls(segment);

georginasCookies(&segmentPtr, &y_food, &x_food, &points, x_buffer, y_buffer);

//Draws the snake head

drawSnake(segmentPtr);

printf("\x1b[%d;%dHO:%p", 10, 10,(void*)&segmentPtr);

// Controls game ticks

Sleep(20);

}

return 0;

}

void georginasCookies(snake** segmentPtr, int* x_food, int* y_food, int* points, int x_buffer, int y_buffer)

{

if ((*segmentPtr)->x_pos == *x_food && (*segmentPtr)->y_pos == *y_food)

{

(*points)++;

addSegment(&segmentPtr, x_buffer, y_buffer);

*x_food = randomBetween(3, 47);

*y_food = randomBetween(3, 27);

printf("\x1b[%d;%dHX", *y_food, *x_food);

}

}

void addSegment(snake** segmentPtr, int x_buffer, int y_buffer)

{

snake* newSegment = malloc(sizeof(snake));

if (newSegment == NULL)

{

printf("Theres no space in memory to run the game");

exit(1);

}

newSegment->x_pos = x_buffer;

newSegment->y_pos = y_buffer;

newSegment->next = *segmentPtr;

*segmentPtr = newSegment;

//printf("\x1b[%d;%dHO:%p", (*segmentPtr)->y_pos, (*segmentPtr)->x_pos, (void*)segmentPtr);

}

void updateSnake(snake* segment)

{

if (segment == NULL || segment->next == NULL)

{

return;

}

// Recorremos desde la cola hacia la cabeza

snake* current = segment;

while (current->next != NULL)

{

current->next->x_pos = current->x_pos;

current->next->y_pos = current->y_pos;

current = current->next;

}

}

//Draws the snake recursively

void drawSnake(snake* segmentPtr)

{

if (segmentPtr == NULL)

{

// Base case

return;

}

// Draws this segment

printf("\x1b[%d;%dHO", segmentPtr->y_pos, segmentPtr->x_pos);

//printf("\x1b[%d;%dHO:%p", 10, 10,(void*)&segmentPtr);

//Sleep(100);

// Calls the function recursively on itself to draw the snake

drawSnake(segmentPtr->next);

}

void windowManagement(int wind_x, int wind_y, int wind_h, int wind_w) {

//Set console size

HWND consoleWindow = GetConsoleWindow();

//Console window x position , y position, height and width

MoveWindow(consoleWindow, wind_x, wind_y, wind_h, wind_w, TRUE);

//Set the buffer size with the same rate as the window

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

COORD coord = { wind_h, wind_w };

SetConsoleScreenBufferSize(hConsole, coord);

}

void controls(snake* segment)

{

//Arrow keys are observed and whenever one is pressed it changes x and y coordinates of the snakes head accordingly

if ((GetAsyncKeyState(VK_LEFT) & 0x8000))

{

segment->x_pos--;

if (segment->x_pos < 0)

{

segment->x_pos = 0;

}

}

if ((GetAsyncKeyState(VK_RIGHT) & 0x8000))

{

segment->x_pos++;

}

if ((GetAsyncKeyState(VK_UP) & 0x8000))

{

segment->y_pos--;

if (segment->y_pos < 0)

{

segment->y_pos = 0;

}

}

if ((GetAsyncKeyState(VK_DOWN) & 0x8000))

{

segment->y_pos++;

}

// Press esc to exit the program

if (GetAsyncKeyState(VK_ESCAPE) & 0x8000)

{

printf("Esc pressed, exiting program...");

exit(0);

}

}

int randomBetween(int min, int max)

{

int value = rand() % ((max + 1) - min) + min;

return value;

}

void freeMemory() // IMPORTANTE NO OLVIDAR LIBERAR LA MEMORIA

{

}

6 Comments
2024/11/19
21:35 UTC

2

Cannot solve errors for unresolved external symbols IID_IMMDeviceEnumerator and CLSID_MMDeviceEnumerator, need help.

Hello, sorry if the answer is obvious here, but I can't figure out how to solve this issue. I am out of ideas on what to do. I am just toying around with WASAPI and want to play some sounds, but the linker cannot find the symbols IID_IMMDeviceEnumerator and CLSID_MMDeviceEnumerator.

Here is the code:

#include <stdio.h>
#include <stdint.h>
#include <Windows.h>
#include <initguid.h>
#include <mmdeviceapi.h>
#include <Audioclient.h>

int main()
{
uint64_t SuccessValue = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (SuccessValue != S_OK)
{
printf("Failed to initialize COM: %llu", SuccessValue);
return -1;
}

IMMDeviceEnumerator* Enumerator;

SuccessValue = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &Enumerator);
if (SuccessValue != S_OK)
{
printf("Failed to initialize enumerator: %llu", SuccessValue);
return -1;
}

CoUninitialize();
return 0;
}

This code is obviously incomplete, but I still cannot get an executable program out of it.

What I've tried:

  • Including #include <initguid.h> at the start, that does not change anything.
  • Linking with uuid.lib
  • Linking with mmdeviceapi.lib (from Microsoft documentation)
  • Tried __uuidof() operator only to find out it was C++ exclusive.

I am using the compiler which comes with Visual Studio.

Any help is appreciated, thank you.

3 Comments
2024/11/19
21:08 UTC

3

Any tips on how to write a parser for a shell?

Trying to implement a BASH-like shell, if you have any tips about parsing shell input I would be very interested, or any good resources on the subject.

11 Comments
2024/11/19
20:54 UTC

0

Does C’s lack of built-in memory safety make it fundamentally outdated, or is this a feature, not a flaw?

Critics often point to C’s manual memory management as a dangerous relic of the past, leading to countless security vulnerabilities and bugs. But others argue that this “freedom” is what makes C so versatile and powerful. Is there a way for C to adopt safer practices without losing what makes it special, or should we accept its trade-offs as part of its design philosophy?

6 Comments
2024/11/19
13:02 UTC

1

I have trouble repeating a function as needed

I've been learning C and making a simple program of D&D character generation to test my knowledge as I go.
I have the following function that needs to be repeated if the user inputs anything apart from 1-4 but it repeats twice.

void chooseClass() {

printf("\n1. Fighter\n2. Thief\n3. Mage\n4. Cleric\nChoose your class: ");

char choice = getchar();

switch (choice - '0') { //Convert character to integer by subtracting 0's ASCII value from char's ASCII value

case 1:

sortFighter();

break;

case 2:

sortThief();

break;

case 3:

sortMage();

break;

case 4:

sortCleric();

break;

default:

printf("Please enter a choice between 1-4\n");

chooseClass(); // this is wrong but how do I repeat the function ONCE?

}

}

I've been banging my head on the wall but no solution has arrived. :-)

18 Comments
2024/11/19
12:21 UTC

0

List of codes to practice

I am beginner in C..just learning stuff... Can someone provide some codes so that I can practice them?

12 Comments
2024/11/19
03:17 UTC

8

Will this macro cause an user after free ? (GCC statement expressions)

#define stream_read_array(stream__, type__, length__) \
    ({\
        struct { type__ data[(length__)]; } __array;\
        stream_read_exactly(stream__, size_and_address(__array));\
        __array.data;\
    })

I think returning the struct works, but does returning the data field work the same, or it does get dropped?

13 Comments
2024/11/18
23:03 UTC

1

Follow on

What do you recommend after:

C Programming Absolute Beginner's Guide Book by Dean Miller and Greg Perry

2 Comments
2024/11/18
21:27 UTC

6

How to Start Learning C for Embedded Systems and Operating Systems? Need Guidance Beyond Introductory Tutorials

Good day everyone. Just joined this subreddit.

I'm a 3rd semester SWE student. Recently I started to grow an interest for Embedded Systems and Operating Systems ( I love GNU/Linux btw). The only course in my degree relevant to hardware and low level stuff is computer architecture and logic design which is a poor attempt to merge DLD and Computer Organisation and Architecture in some 4 month unified course. They added it as formality considering hardly 5% or so will go into embedded or low level side of software engineering.

My question is that how should I start diving into C . I have basic knowledge of C++ and somewhat C#. I tried to get into Rust as my first systems programming language but I gave up on it and realised it's not a good idea. Idc what rustaceans say. People around me mainly proud noobs have this idea that C is obsolete and C++ is some "new version or upgrade" to C. Who's gonna tell them . I use example of automatic and manual car to tell the difference (I hope it's not a bad example)

I have seen many people recommending K&R book as one of the main source. Don't want to get into YouTube tutorial hell as most of C lang tutorials I come across are repetitive introductory courses. They don't usually conclude till the part where real power of C has to be demonstrated i.e low level tasks and applications. If I manage to find one they're either too old or no longer continued.

Still I'd be grateful if a good YouTube playlist or channel which follows C language step by step till the concepts of embedded, operating systems, memory management or any related low level stuff expected to do using a systems programming language like C.

4 Comments
2024/11/18
05:52 UTC

41

Using hashmaps instead of classes?

I was just thinking if we could just write a hashmap struct that stores void pointers as values and strings as keys, and use that for OOP in C. Constructors are going to be functions that take in a hashmap and store some data and function pointers in it. For inheritance and polymorphism, we can just call multiple constructors on the hashmap. We could also write a simple macro apply for applying methods on our objects:

#define apply(type, name, ...) ((type (*)()) get(name, __VA_ARGS__))(__VA_ARGS__)

and then use it like this:

apply(void, "rotate", object, 3.14 / 4)

The difficult thing would be that if rotate takes in doubles, you can't give it integers unless you manually cast them to double, and vice versa.

34 Comments
2024/11/18
14:50 UTC

0

Large number formatting in code

Hey is there way to make large numbers more readable? i search but I couldn't find anything, what I mean is separation of zeroes so instead of writing

int a = 100000;

I want something like

int a = 100_000;

Or whatever is available to make it readable in code, I tried spaces, ' and _ but got errors. I use gcc to compile

10 Comments
2024/11/18
11:32 UTC

11

Do you need a contributor? Whatcha working on?

Hi! I'm currently job hunting and have some measure of spare time (and want to buff up my resume) so I'm looking for meaningful projects to contribute to.

So I'm screaming into the void hoping to find some projects to contribute to!

Do let me know, I'm happy to help (if my skills are sufficient).

I say meaningful because it's important to me that the project is important to you (or that you're passionate about it).

19 Comments
2024/11/18
11:24 UTC

0

segmentation fault probl.

Hi there, i think there should be a segmentation fault problem with my code, but i cant find it. Can someone help me? (the code should sort the arrey and delete all the duplicates)

#include <stdio.h>
#define N_MAX 1000


int main () {
    int v[N_MAX], n;
    int temp=0;
    
    printf ("how many values do u wanna insert?\n");
    scanf("%d", &n);
    
    printf ("write your values:\n");
    for (int i=0; i<n; i++) {
        scanf("%d", &v[i]);
    }
    
    for (int i=0; i<n-1; i++) {
        for (int j=0; j<n-1; j++) {
            
            
            while(i!=j) {
                
                if (v[i]==v[j]) {
                    
                    temp=v[n-1];
                    v[n-1]=v[j];
                    v[j]=temp;
                    
                    n=n-1;
                }
            
            }            
        }
                
    }
    
    
    
    
    for (int i=0; i<n-1; i++) {                //final bb sort
        for (int j=0; j<n-1-i; j++) {
            if (v[j]>v[j+1]) {
                temp=v[j];
                v[j]=v[j+1];
                v[j+1]=temp;
            }
        }
    }
    printf("\n");
    for (int i=0; i<n; i++) {
        printf ("%d\t", v[i]);
    }
    printf ("\n");
}
11 Comments
2024/11/18
00:48 UTC

4

Inline visual debugger like Thonny

For Python there is an IDE with a great visual debugger, named Thonny. You can see a very short and descriptive video with the debugger in action here: https://www.youtube.com/watch?v=tehY3ZFVPmE

Is there a similar C debugger which shows you inline how things are executed?

Later edit:

At 0:50 in the video it shows exactly what I mean.

I will not use the debugger for actual development.

I'm searching for such a tool for teaching purposes, not actual development. I'm looking for a visual animated experience, which does not need to look elsewhere than the line the debugger is executed in order to see what's happening. The video I've provided is 1-2 minutes, and I've chosen it exactly because it proves what I'm trying to achieve with a quick demo.

5 Comments
2024/11/17
18:45 UTC

0

JavaScript to C: Can you do this without an online code translator/converter?

This Web site Convert JavaScript to C using AI claims

Source-to-source code translation from JavaScript using AI involves utilizing natural language processing (NLP) techniques and machine learning algorithms to analyze and understand source code

And spits out C that works when compiled to achieve the same result (minus dynamic arguments passing) as JavaScript.

How would you go about achieving this locally?

6 Comments
2024/11/17
18:20 UTC

0

Recursion in C

define a recursive function that will print all possible
passwords from a set of characters in an array.
Example: if arr[]={‘a’,’b’,’c’} function should print
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc

can someone help

10 Comments
2024/11/17
18:00 UTC

66

Can’t put my finger on why I don’t like Golang

Posting in this sub because I want to hear what C programmers think about Go.

Go is not sitting well with me as a language and I’m not sure why. On paper it is almost the perfect language for me - it’s relatively low level, it’s very simple to do web dev with just std libs (I do a lot of web dev), GC makes it safer, it values stability and simplicity, it has a nice modern package manager, it has a great ecosystem, and it’s designed to “fix the problems with C”.

But for some reason it just doesn’t give me the same joy as programming in C. Maybe I feel nostalgic towards C because it was my first language. Maybe I prefer the challenge of dealing with the quirks of less modern tools. For some reason C has always made me feel like a “real programmer”, more-so than any other language.

Obviously C is better suited to some niches (systems, etc) and Go is better suited to others (web dev). I’m interested in discussing the merits and values of the languages themselves. Maybe they are not even comparable. Maybe Go should be thought of as a modern C++ rather than a modern C.

Anyway, I would love to hear some thoughts opinions of others on this sub.

93 Comments
2024/11/17
17:30 UTC

8

whats a good book to start learning C?

hi, i wanna start learning C to begin learning coding, but i read that the original "The C programming language" is outdated. does anyone know a good book thats to date to start? thanks

10 Comments
2024/11/17
16:33 UTC

0

This is too much?

Hello everyone, I’m here to ask something that I’m really interested in.

So I want to make an AI that can work in forex, I mean like search for resistance/support, use VWAP search for trend etc.

And have a feature that he can talk like ChatGPT.

And he is integrated to its host computer, when you start the computer he start too, he has his application where you can talk with him, and you can give him orders , like search for viruses, start chrome with the title: best movies. He can search through the net, he can open apps and close them. He can use live forex charts..

I mean he is open for everything, in legal manners!!!

. (Little Jarvis, if you know what I mean)

Can anybody help me to build him? This ai would be very much help to me…

Thank you for your answers. Have a grate day.

7 Comments
2024/11/17
15:27 UTC

0

How to do the mingw to code in c/c++

Hello i'm on windows and I have been trying to code in c but i watched a YouTube saying I have to do the mingw process on sourceforge and it's been frustrating when I press next it just disappears can someone please help me I am very dedicated thanks

8 Comments
2024/11/17
15:15 UTC

22

Does C23 have a defer-like functionality?

In Open-STD there's a proposal (N2895) for it, but did it get accepted? Or did the standard make something different for the same purpose?

33 Comments
2024/11/17
15:08 UTC

0

Comfusing about the problem of factorial

No.1

#include<stdio.h>

#include<math.h>

double factorial(int n)

{

int i;

double result = 1.0;

for (i = 1; i <= n; i++)

{

	result = result \* i;



}

return result;

}

double everystep(int N, int M)

{

return(double)factorial(N) / (factorial(N - M) \* factorial(M));

}

int main()

{

double b;

int n;

int i;

double sum = 0.0;

scanf\_s("%d %lf", &n, &b);

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

{

	sum = sum + everystep(n, i) \* pow(b, i);

}

printf("%.8f", sum);

return 0;

}

No.2

#include<stdio.h>

#include<math.h>

double factorial(int n)

{

if (n == 1)

{

	return 1;

}



return(double)n \* factorial(n - 1);

}

double everystep(int N, int M)

{

return(double)factorial(N) / (factorial(N - M) \* factorial(M));

}

int main()

{

double b;

int n;

int i;

double sum = 0.0;

scanf\_s("%d %lf", &n, &b);

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

{

	sum = sum + everystep(n, i) \* pow(b, i);

}

printf("%.8f", sum);

return 0;

}

Two different ways to show the factorial,but way2 didn"t work ,can you tell me the reason?Thanks!

The issue lies in the factorial function that I've created.

3 Comments
2024/11/17
12:33 UTC

Back To Top