/r/C_Programming
The subreddit for the C programming language
Click the following link to filter out the chosen topic
/r/cjobs – for C programming jobs
/r/cprog – another subreddit for articles and discussions
/r/C_Homework – another subreddit for questions
/r/C_Programming
I want to make a private network like Tor but only as a private net. My goal is an app where I can search for my website.customextension for example and that it's hosted in other computer. Simple as that the idea, but I don't know where to start. Something that's not in the clear net.
Please solve this problem
This post is a followup to my earlier one: https://www.reddit.com/r/C_Programming/comments/1gmx9i0/i_made_a_portable_package_manager_for_tarballs/ - I'm posting this as an update and to let others know. If people consider this spam, I'll stop writing about this project here.
Following requests and suggestions from people on this and other subs, I added support for ARM64 on Linux and x86-64 (Intel) macs. This, of course, only applies to the package manager itself, packages distributed for an architecture cannot magically be used on another. Windows support is not in-tree yet.
I also added an update command which should make it easier to update installed packages, along with a remove-repo command to remove local repositories you no longer need, and a version commands that gives you information on the version of tarman and the compiler used to build it.
These may seem tiny changes, and for sure they're not huge, but I felt they were important enough for an early-dev project to publish this post.
If you have tarman on your system already, you should be fine with:
tarman install -r tarman
Otherwise, check out the GitHub Repo, you'll find instructions on how to install it in the README. Future updates will only require users to enter
tarman update tarman
I recently read an interesting old Reddit thread about the practice of "asking for stars" on GitHub. I've honestly never done it publicly and I'd like to know your opinion and, possibly to get some feedback on GitHub directly. So, may I humbly invite you to leave feedback if you find this interesting (issues, PRs, watching, starts, whatever). Again, I've never done this, I just want to know whether people consider this "begging" or if it genuinely helps gather feedback on GitHub. Cheers.
There are many playlists on MIT channel
struct vec2 {
float x;
float y;
}
#define V ...
V(5, 10) -> (5.0, 10.0)
V(5) -> (5.0, 5.0)
V() -> (0.0, 0.0)
I need to decode a string that is base64 encoded. Moments like this make me miss python lol. What is the easiest way for me to do this.
Yeh, how do I make a custom compiler in C, is there any template I can use? Or is it mandatory to write a 1M line file just to translate an if statement to ASM
NOTE: not meant to make fun of actual proposals, but to imagine things that you could imagine being an actual extension to the language some compiler implements, but should probably never be included in the spec.
Here's the idea that made me want to make this thread: post-fix assignment operator
Doesn't really matter what the syntax would be, but for example let say the operator is $=
, because that's not used by anything so it wont be confusing.
a $= b
would return the value of a
, and then assign b
to a
as a side effect.
For example:
int a = 1;
printf("%d,", a $= 2);
printf("%d", a);
would output 1, 2
.
This came to me in a dream wherein I wanted to turn free(ptr); ptr = NULL
into a one-liner.
I am working on a programming assignment in C. The project has a CMakeLists.txt file, which i use to build a makefile. Then this makefile is used to build the binary to run. Now when i execute this binary from the integrated terminal of the IDE (CLion & VS Code) it works fine, passes all test cases. But when the same binary is executed in the system terminal i get a Segmentation Fault (Core dumped) error. Why does the error only occurs in the system terminal and not in any IDEs integrated terminal?
Any help is appreciated. Sorry for my bad english. I have added the commands execution order, so my problem makes a bit more sense.
I am on Ubuntu 24
Order of executions:
cmake .
make
./test
The same binary regardless if it was generated using the system temrinal or the IDEs terminal, when run give error in system terminal and not in the IDEs terminal.
Github Repo containing project code - https://github.com/kamakshyan/DB_Assignment_2
EDIT 1: Added project code
EDIT 2: Not sure about the difference in system and integrated terminal behaviour, but fixing the unclosed file descriptors resolved the issue.
I know this is probably one of those "it's one of the many tools you can use to solve a problem" kinda things, but why would one ever prefer recursion over just a raw loop, at least in C. If I'm understanding correctly, recursion creates a new stack frame for each recursive call until the final return is made, while a loop creates a single stack frame. If recursion carries the possibility of giving a stack overflow while loops do not, why would one defer to recursion?
it's possible that there are things recursion can do that loops can not, but I am not aware of what that would be. Or is it one of those things that you use for code readability?
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:
array
and array1
.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!
Hi, I’m currently trying to:
I’m using strtok and am able to read the file as separate lines, but cannot figure out how to make each line defined independently.
My end goal is to run each line into a function individually.
Any help would be amazing, I’m a complete newbie to programming.
Hello! I'm pretty new to C and I've been going through a college course for it and we have a project to design a calculator for an RLC series circuit. The problem is I've been struggling with with getting the exponents to be properly rounded in engineering notation. I've tried using a log to get it to be in proper notation but no dice. IF anyone has any advice or can help that would be much appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
float input_voltage, frequency, resistance, inductance, capacitance;
char confirm;
printf("==============================\n");
printf("|ENGINEERING NOTATION VALUES |\n");
printf("|Kilo 3 |Mili -3|\n");
printf("|Mega 6 |Micro -6|\n");
printf("|Giga 9 |Nano -9|\n");
printf("|Tera 12 |Pico -12|\n");
printf("|Peta 15 |Femto -15|\n");
printf("|Exa 18 |Atto -18|\n");
printf("|Zetta 21 |Zepto -21|\n");
printf("==============================\n\n\n");
float FalseReturn(float base)
{
float exponent = log10f(base);
float Remainder = fmod(exponent, 3);
if (Remainder != 0) {
printf("================================\n" );
printf("THE AGONY THAT I RAISE %f\n", exponent );
printf("EVERYDAY I WAKE UP IN REMAINING %f\n", Remainder );
printf("ONE DAY IN THE BASE %f\n", base );
return base * pow(10, exponent);
}
printf("================================\n" );
printf(" RAISED %f\n", exponent );
printf("REMAINING %f\n", Remainder );
printf("BASE %f\n", base );
printf("================================\n" );
printf("================================\n" );
printf("CALCULATED\n" );
exponent -= Remainder; // exponent set to smaller increment of 3
Remainder =(int)Remainder;
Remainder = pow(10, Remainder); // 2^10 --> 00.
base = base/Remainder; // 50 * 100.00 = 50,000 e+3
printf(" RAISED %f\n", exponent );
printf("REMAINING %f\n", Remainder );
printf("BASE %f\n", base );
printf("================================\n" );
return base;
}
float get_engineering_value(const char *quantity) {
float base, exponent;
int result;
printf("Please input the base value for your %s (e.g., 1.0): ", quantity);
result = scanf("%f", &base);
// Check if the input for base is valid
if (result != 1) {
printf("Error: Invalid input. Please enter a number.\n");
scanf("%*s"); // Clear the invalid input
return get_engineering_value(quantity);
}
getchar(); // Clear newline or extra input
printf("Please input the exponent for your %s (must be a multiple of 3): ", quantity);
result = scanf("%f", &exponent);
// Check if the input for exponent is valid
if (result != 1) {
printf("Error: Invalid input. Please enter a number.\n");
scanf("%*s"); // Clear the invalid input
return get_engineering_value(quantity);
}
getchar(); // Clear newline or extra input
// Validate that exponent is a multiple of 3
if (fmod(exponent, 3) != 0) {
printf("Error: Exponent must be a multiple of 3. Try again.\n");
return get_engineering_value(quantity);
}
return base * pow(10, exponent);
}
// Input for each value using engineering notation so they can be stored and used later
input_voltage = get_engineering_value("Source Voltage (V)");
frequency = get_engineering_value("Source Frequency (Hz)");
resistance = get_engineering_value("Resistance (Ohms)");
inductance = get_engineering_value("Inductance (H)");
capacitance = get_engineering_value("Capacitance (F)");
// Confirm values using loop
printf("\nAre these your values? (y/n): \n");
printf("Voltage: %e V\n", input_voltage);
printf("Frequency: %e Hz\n", frequency);
printf("Resistance: %e Ohms\n", resistance);
printf("Inductance: %e H\n", inductance);
printf("Capacitance: %e F\n\n", capacitance);
scanf(" %c", &confirm); // Y/N prompt for user
if (confirm == 'n' || confirm == 'N') {
printf("Okay, let's try again.\n\n");
main();
} else {
// Corrected calculations
float XL = (2 * M_PI * frequency * inductance); // Inductive reactance
float XC = 1 / (2 * M_PI * frequency * capacitance); // Capacitive reactance
float impedance = sqrt(pow((XL - XC), 2) + pow(resistance, 2)); // Circuit impedance
float IT = input_voltage / impedance; // Total circuit current
float VL = IT * XL; // Voltage across inductor
float VC = IT * XC; // Voltage across capacitor
float VR = IT * resistance; // Voltage across resistor
// Corrected phase angle calculation (convert from radians to degrees correctly)
float phase = atan((XL - XC) / resistance) * (180 / M_PI); // Total phase angle in degrees
//Convert to proper notation form
// Use FMOD to find the remainder of our exponent
// use FMOD to find the notation we should be in
// example: X^7 --> X*1^6
// here we rip out our exponent until we find a multiplicity of three, then raise our base to our remainder.
// exponent: 17
// Closest: 15
// exponent - remainder value ()
// Display results
printf("\nCalculated Results:\n");
printf("Inductive Reactance (XL): %e ohms\n", FalseReturn(XL));
printf("Capacitive Reactance (XC): %e ohms\n", FalseReturn(XC));
printf("Circuit Impedance (Z): %e ohms\n", FalseReturn(impedance));
printf("Total Circuit Current (It): %e amps\n", FalseReturn(IT));
printf("Voltage across Inductor (VL): %e volts\n", FalseReturn(VL));
printf("Voltage across Capacitor (VC): %e volts\n", FalseReturn(VC));
printf("Voltage across Resistor (VR): %e volts\n\n", FalseReturn(VR));
printf("Total Circuit Phase Angle: %f degrees\n\n", phase);
// Ask if the user wants to perform calculations again
printf("Would you lsike to perform the calculations again? (y/n): ");
scanf(" %c", &confirm);
if (confirm == 'y' || confirm == 'Y') {
printf("Okay, let's go again.\n\n");
main();
}
// Credits
printf("=======================================================================\n");
printf("Thank you for using our program! Hope to see you again.\n");
printf("\nProgrammed by Andres Herrera, Holly-June James, and Josh Halliburton.\n");
printf("Made possible by Code::Blocks.\n");
printf("Compiled by GCC Compiler.\n");
printf("And you, the user <3\n");
printf("=======================================================================\n");
return 0;
}
}
Where can i get ideas for projects or projects that helped you get better understanding of c
What programming language should I learn as a begginner? In school, I study C++ but not at a advanced level. What do you think?
Joseph's problem
The program I've provided implements a version of the Josephus problem. In this problem, 30 people are standing in a circle, and every 7th person is eliminated until only one remains. The remaining people are output in the order in which they were eliminated.
but it doesn't work,please help me with it ,thanks
#include <stdio.h>
int main() {
int allbody[30] = { 1 }; // 30 people, all initially not eliminated (1 means alive)
int count = 0; // Counter to track the number of steps
int count_out = 0; // Counter to track the number of people who have been eliminated
int outpeople[30] = { 0 }; // Array to store the positions of eliminated people
int k = 0; // Current position being checked
// Start a loop until all 30 people are eliminated
while (count_out < 30) {
if (allbody[k] != 0) {
count = (count + 1) % 7; // Increase count by 1, and wrap it around to 0 after reaching 6
if (count == 0) { // When the count reaches 0, the person is eliminated (every 7th person)
outpeople[count_out] = k; // Record the position of the eliminated person
count_out++; // Increment the eliminated people counter
allbody[k] = 0; // Mark this person as eliminated (0 means eliminated)
}
}
k = (k + 1) % 30; // Move to the next position in the circle, wrap around using modulo 30
}
// Output the elimination order (add 1 to convert from 0-based to 1-based index)
for (int q = 0; q < 30; q++) {
printf("%d\n", outpeople[q] + 1); // Output the eliminated person number (1-indexed)
}
return 0;
}
Hi all,
So I'm mostly a C++ and Zig programmer, and wanting to expand my horizons and get better at writing C, and writing it decently. I'm much more familiar with writing code in an OOP style because of my time writing C++, and was wondering if anyone would recommend these books or another resource for DSA specifically in C. I did a bit of prior searching on this subreddit and found a couple different YT videos (that were several hours long) on DSA in C, but I was wanting a more in depth exposure to the subject(s). I also read that Sedgewick C DSA requires Knuth-level math knowledge to get through. I'm not sure what that entails as I've been teaching myself calculus (1) and have just gone over limits, series, and derivatives. So I'm not sure if I should just continue self-teaching calc before going through the books or if I should be able to get through the books relatively easily without the aforementioned math skills.
Thanks in advance for your responses!
My question essentially is whether the two functions at the bottom of this post can be made more efficient, perhaps by making them branchless. But for the functions to make sense, I feel like I need to give some background.
Background:
I am using a specific implementation of circular, doubly linked lists.
I have a network with nodes 0, 1, 2, ..., n-1
, and each node has an associated cost that can itself be a number in 0, 1, 2, ..., n
. Multiple nodes can have the same cost (and they probably do).
As the program runs, the cost of each node may change.
What I need is to have quick retrieval of a node with cost k
for any k (if there is such a node at that moment).
To this end, I organize the data as follows: for each cost k
, all the nodes with cost k
are in a circular, doubly linked list. This way, if I want to retrieve a node with cost k
, I can just check the corresponding list.
Now, since the node costs change all this time, this data structure needs to be kept up to date. This can be done very efficiently because insertion and deletion in a doubly linked list are both O(1) time.
The implementation uses the following arrays:
int *entries = malloc( (n + 1) * sizeof(int) ) ;
int *fwd = malloc( n * sizeof(int) ) ;
int *rev = malloc( n * sizeof(int) ) ;
entries[k]:
Any node with cost k, if such a node exists. If no such node, then -1.
This node serves as an entry point into the circular, doubly linked list corresponding to k.
fwd[i]:
The idea is that if you chase i using the fwd array, as in
i, fwd[i], fwd[fwd[i]], ...
you generate all nodes in the same linked list as i (that is, all nodes with the same cost as i). Typically, i is selected as i = entries[k].
rev[i]:
Same as fwd[i], in that
i, rev[i], rev[rev[i]], ...
will generate the entire linked list containing i, but rev is in the reverse order as fwd. That is, whenever fwd[i] = j, then rev[j] = i, and vice versa.
Example:
Let's say n = 5. The nodes are 0, 1, 2, 3, 4 and the costs can be between 0 and 5, inclusive. Let's say the node costs are 2, 2, 3, 2, 3. Then
// entres[2] = 0 which is a node with cost 2, and entries[3] = 4, which is a
// node with cost 3.
entries = -1 -1 0 4 -1 -1
// In fwd, 0 -> 3 -> 1 -> 0 (these are the nodes with cost 2) and 2 -> 4 -> 2
// which are nodes with cost 3
fwd = 3 0 4 1 2
// In rev, 0 -> 1 -> 3 -> 0 (the nodes with cost 2) and 4 -> 2 -> 4 (nodes with cost 3)
rev = 1 3 4 0 2
Finally, here are my functions for inserting and deleting in these circular, doubly linked lists:
static void ll_delete
(
int node, // to be deleted
int cost, // cost of the node
int *entries,
int *fwd,
int *rev
)
{
int next = fwd[node] ;
if(next != node) // size of list is > 1
{
// Change prev <--> node <--> next to prev <--> next
int prev = rev[node] ;
fwd[prev] = next ;
rev[next] = prev ;
entries[cost] = next ; // in case entries[cost] is to be deleted
}
else // size of list was exactly 1
{
entries[cost] = -1 ;
}
}
static void ll_insert
(
int node, // to be inserted
int cost, // cost of the node
int *entries,
int *fwd,
int *rev
)
{
int entry = entries[cost] ;
if(entry == -1)
{
entries[cost] = node ;
fwd[node] = node ;
rev[node] = node ;
}
else
{
int next = fwd[entry] ;
// enty -> node -> next
fwd[entry] = node ;
fwd[node] = next ;
// next -> node -> entry
rev[node] = entry ;
rev[next] = node ;
}
}
Hello, I am using typedefs to provide enhanced readability for more complex types. An example of this would be a map type that can hold ints and floats. Without these typedefs, I could not tell what types the map could hold. I have done a little research, and I have seen people say to not use typedefs too often. However, those people never mentioned my use case, so I'm a bit unsure as to whether or not I am doing the right thing by using them like this.
Here is the link to the full WIP project code: Crawfish-h/CFT: A c project that adds a sort of dynamic type system.
Pseudo-ish code example:
typedef struct FMap // I am not talking about typedef structs.
{
TArray(Key) Keys_;
void* Values_;
size_t Size_;
size_t Capacity_;
FVector Value_Types_;
} FMap;
// I'm talking about this...
#define FMap(...) typedef FMap ## Concatenate(__VA_ARGS__); FMap ## Concatenate(__VA_ARGS__)
int main(int argc, char* argv[])
{
FMap map_0;
// This allows for me to hover over map_1 with my mouse and see the types it can hold.
FMap(int, float, char*) map_1;
Map_Init(map_0, bool, int);
Map_Init(map_1, int, float, char*);
// Map_Init(...) and FMap(...) could probably be combined to allow for cleaner code but thats
// for later.
}
#include <stdio.h>
#define LOOP_UNTIL_COUNTER(MAX_COUNT)\
{\
for (int counter=0; counter<MAX_COUNT; counter++)
#define END_LOOP_UNTIL_COUNTER()\
}
int main() {
LOOP_UNTIL_COUNTER(5)
{
printf("hello\n");
}
END_LOOP_UNTIL_COUNTER();
return 1;
}
This just isn't clicking in my brain. I've never seen a macro like this, I don't understand what's going on. How does this printf statement get repeated within the macro the set number of times? How does that END_LOOP_UNTIL_COUNTER() bit work? I'm so lost I don't even really know what specific questions to ask
Please suggest some good projects. I want to understand what kind of things I can work on related to OS and DS after studying C and linux interface. TYIA.
#include <stdio.h>
#include <string.h>
#define max 10
char prefix[100], postfix[100];
int top = -1;
char stack[max];
int push(char data){
if(top < max -1 ){
stack[++top] = data;
return 0;
}
return 1;
}
char pop(){
if(top == -1){
return 0;
}
if(top == 0){
top = -1;
return stack[0];
}
return stack[--top];
}
void display(){
for(int i = 0; i <= top; i++){
printf("%c",stack[i]);
}
printf("\n ");
}
int is_operator(char symbol)
{
if (symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')
return 1;
else
return 0;
}
int precedence(char symbol)
{
if (symbol == '^')
return 3;
else if (symbol == '*' || symbol == '/')
return 2;
else if (symbol == '+' || symbol == '-')
return 1;
else
return 0;
}
void prefixToPostfix(){
int n = 0, curr = 0;
int prev, now;
char x;
for(char c = prefix[n]; c != '\0'; n++, c=prefix[n]){
if ( c == '('){
push(c);
}
else if(is_operator(c)){
printf("Operator\n");
x = pop();
now = precedence(c);
prev = precedence(x);
if(prev > now){
printf("HA\n");
while(prev > now){
postfix[curr] = x;
curr++;
x = pop();
prev = precedence(x);
}
push(x);
}
else{
push(x);
}
push(c);
}
else if(c == ')'){
x = pop();
while(x != '('){
postfix[curr] = x;
x = pop();
}
}
else{
postfix[curr] = c;
curr++;
}
}
while(top != -1){
printf("Emptying ");
x = pop();
printf("Postfix: %c \n", x);
postfix[curr] = x;
curr++;
}
postfix[curr] = '\0';
}
int main(){
printf("Prefix: ");
scanf("%s", prefix);
prefixToPostfix();
printf("Postfix: %s", postfix);
return 0;
}
smone else help the operators arent being appended to the string
A YT named HackerCS made years ago, two videos about reading and writing C type declarations. He explains in a very clear and pedagogical way howto.
I'm in my third year of learning C and I admit I got some challenges.
https://www.youtube.com/watch?v=yY1DK5gCRxA&list=PLn3A1FGnKiUzerbdW4Zdp3-urUG27-TKV&index=6
Hi guys
I have a bad experience with C formatters, and was wondering if someone here has a different experience.
This is basically how I want code to look like:
static
__attribute__((always_inline))
inline
status_t
_do_stuff1(
size_t arg1,
size_t arg2
) {
status_t status = STATUS_FAIL;
if ((status = ask_redit(
"about a",
"c formatter
)) != STATUS_SUCCESS
) {
goto cleanup;
}
if ((status = ask_redit_again("last time"))) != STATUS_SUCCESS) {
goto cleanup;
}
for (size_t i = 0; i < 42; i++) {
..
}
cleanup:
return status;
}
static
__attribute__((always_inline))
inline
status_t
_do_stuff_2(
size_t arg1
) {
...
}
static
__attribute__((always_inline))
inline
status_t
_do_stuff3(void) {
...
}
Does anyone has suggestions for a formatter + config file?
I've been using a form of "object pools" in a recent C project of mine (though the term might not be a perfect fit). By "object pools," I mean: contiguous arrays of components (automatically sorted by whether they're active/in use, with each component having its own pool), which can then be processed in batches during the main program loop (i.e., doing all of the X components, then all of the Y components, etc.).
For data locality reasons, these arrays store the raw objects themselves, not pointers to said objects. Furthermore, due to the limitations of the platform that I'm developing for, I'm exclusively using static allocation for these pools.
This approach has been working perfectly fine, but there is some duplicate code between all of these different component pools, which my monkey brain tells me is not ideal. I understand that this might just be a given when working with C, but is there a better, more generic approach out there?
Ideally, all of these components could have some ObjPool_t
data field which would encapsulate some of this duplicate code, but I haven't come up with a good, non-hacky solution which might apply here. Lastly, the solution, should one exist, should be ANSI C compatible due to the limitations of the SDK I'm using.
My current (and untested) approach would be to use a union as the type of/size for the underlying array, where this union contains one of every component within it. Not sure if this would work in practice, however, as I haven't gotten around to testing it.
Any thoughts? If I don't wanna get too hacky with it, am I just stuck with duplicate code? Thanks!
HI, so these days I am trying to port a ncurses web app to the browser, so I am using termlib.js and EMScripten to make a small C library named webcurses in order to achieve that.
I found some unfinished projects about it, so I decided to give it a try and see if I can use it to learn WebAssembly. If anyone have any advice, I would appreciate it a lot
Source of what I am trying to do: https://github.com/Stradex/webcurses
This may help some people starting to learn C syntax.
It converts text to code for if statements user input and more.
Its best used in a terminal emulator that splits screens.
It's my first year in computer science and I'm feeling so lost.
At some point, I think the topics that are being taught to us are pretty simple. However, here lies the problem, I'm finding it hard to understand what's happening in major subjects. Especially with programming. We are currently learning about C, I'm struggling a lot on understanding how does it work when I have to apply it directly. I can understand some of its parts and functions, but when I have to apply them, I become so lost.
I am also struggling with writing algorithms as well as flowcharts. It feels like I should have mastered this first before having the guts to try and understand. At some point, I could not do anything because I could not keep up with the flow of our lessons.
In a about a few days, we'll have to solve for machine problems and we'll have to code again in C. Do you guys have any tips on how I can get better at coding even just a little? I'm really scared right now. Despite being scared, I don't want to let go of my program.
I would greatly appreciate anything, guys. Please help me out.