/r/cprogramming
A Subreddit dedicated to the C programming language. Everything related to C is welcome here.
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
Imperative (procedural), structured
Dennis Ritchie
Dennis Ritchie & Bell Labs (creators);
ANSI X3J11 (ANSI C);
ISO/IEC JTC1/SC22/WG14 (ISO C)
1972 (48 years ago)
C18 / June 2018 (2 years ago)
Static, weak, manifest, nominal
Cross-platform
.c for sources
.h for headers
C++ is not C (but C can be C++)
For C++ go to :
Other Resources
/r/cprogramming
Hello I am a student and was given a .h file with the appropriate structure and function proprototypes and left to implement them. I was also provided a test driver. I pass all the tests but the last one which I believe involved queuing and dequeueing values at the limit of the queue. GPT hasn't been any help and alot of what I find online are implementations where there seems to be a check for if the queue is full and will not add amd just inform on the status.
This implementation needs to "wrap around" and replace vues at the tail once it becomes full.
I would appreciate any insight or guidance becuase it seems like the solution should be simple but I have been stuck on this embarrassingly long.
Code:
#include "circular.h"
void CircularInitialize(CircularQueue *q) // Sets up initial values for the circular queue
{
q->count = 0;
q->head = 0;
q->tail = 0;
}
void CircularEnqueue(CircularQueue *q, int value)
{
if (q->count < QUEUE_SIZE) { // Queue is not full
q->data[q->head] = value;
q->head = (q->head + 1) % QUEUE_SIZE;
q->count++;
} else { // Queue is full (wraps around)
q->tail = (q->tail + 1) % QUEUE_SIZE;
q->data[q->head] = value;
q->head = (q->head + 1) % QUEUE_SIZE;
}
}
int CircularDequeue(CircularQueue *q, int *pValue)
{
if (q->count > 0) { // Queue is not empty (can dequeue from tail)
*pValue = q->data[q->tail];
q->tail = (q->tail + 1) % QUEUE_SIZE;
q->count--;
return 0; // Success
}
return 1; // Queue is empty, cannot dequeue
}
I was writing a OpenMPI Program to calculate the factorial of a number.
At first I wrote this abhorrent code:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int calculateBounds(int n, int rank, int size, int* lowerBound, int* upperBound);
int multiplyRange(int lowerBound, int upperBound);
int mMin(int a, int b);
int mMax(int a, int b);
int main(int argc, char* argv[]){
int mRank, mSize;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mRank);
MPI_Comm_size(MPI_COMM_WORLD, &mSize);
int userInputN = atoi(argv[1]);
if(mRank == 0){
printf("calculating factorial of: %d with %d process\n", userInputN, mSize);
}
if(mRank == 0){
//testing
int lower, upper;
for(int i = 0; i < mSize; i++){
calculateBounds(userInputN, i, mSize, &lower, &upper);
printf("[%d, %d] = %d\n", lower, upper, multiplyRange(lower, upper));
}
}
MPI_Finalize();
return 0;
}
int multiplyRange(int lowerBound, int upperBound){
// multiplies in range [lowerBound, upperBound)
int result = 1;
for(int i = lowerBound; i < upperBound; i++){
result *= i;
}
return result;
}
int calculateBounds(int n, int rank, int size, int* lowerBound, int* upperBound){
int scale = mMax(n / size, 1);
*lowerBound = 1 + (rank * scale);
if (rank == (size - 1) ){
*upperBound = n + 1;
}
else {
*upperBound = (*lowerBound) + scale;
}
}
int mMin(int a, int b){
return (a < b) ? a : b;
}
int mMax(int a, int b){
return (a > b) ? a : b;
}
Then I came up with this better program:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
int mRank, mSize;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mRank);
MPI_Comm_size(MPI_COMM_WORLD, &mSize);
int userInputN = atoi(argv[1]);
if(mRank == 0){
printf("calculating factorial of: %d with %d process\n", userInputN, mSize);
}
int localResult = 1;
for(int i = (2 + mRank); i <= userInputN; i += mSize){
localResult *= i;
}
int total;
MPI_Reduce(&localResult, &total, 1, MPI_INT, MPI_PROD, 0, MPI_COMM_WORLD);
if(mRank == 0){
printf("factorial of: %d = %d\n", userInputN, total);
}
MPI_Finalize();
return 0;
}
Hi there!
I am new to C programming language, and wish to make a game using SDL2 which is a uni project. I can't use C++, since they have only allowed C. I am following a SDL2 tutorial, however since the tutorial uses C++, I can't use classes. I have to use structs, and have separate Init, and Destroy functions. However I am conflicted with the methods used to init, and destroy these structs. I have a Entity which is a struct which is instantiated like so. Which one is better:
SDL_Texture* texture = RenderWindow_loadTexture(&window, "path/to/image.png");
Entity* entity = Entity_Init(20, 40, 50, 417, texture):
//Entity.c
Entity* Entity_Init(
const float x, const float y,
const int size, const int textureSize, SDL_Texture* texture
)
{
Entity* entity = malloc(sizeof(Entity));
if (entity == NULL) {
free(entity);
return NULL;
}
entity->x = x;
entity->y = y;
entity->viewRect.x = 0;
entity->viewRect.y = 0;
entity->viewRect.w = textureSize;
entity->viewRect.h = textureSize;
entity->size = size;
entity->texture = texture;
return entity;
}
Entity entity;
Entity_Init(&entity, 200, 40, 40, 450, texture);
//Entity.c
void Entity_Init(
Entity* entity,
const float x, const float y,
const int size, const int textureSize, SDL_Texture* texture
)
{
entity->x = x;
entity->y = y;
entity->viewRect.x = 0;
entity->viewRect.y = 0;
entity->viewRect.w = textureSize;
entity->viewRect.h = textureSize;
entity->size = size;
entity->texture = texture;
}
Guys, I was learning C programming after I gave up Web development (I learnt it, built projects for 3 years). I am extremely interested in how to build OS, how it works, how to build kernel, drivers, bootloader and so on. Can I become OS developer if I stay consistent and work hard?
I’ve been doing C for a few months, and I’ve been loving it. But what even is the point of this lang? Apparently, C++ gives just as much, if not more fundamental knowledge about programming, it performs basically the same, except C++ is more relevant and is used by more companies, while most companies don’t seem to care about C when they can just use C++. Am I just wasting time? I’ll still continue to learn it because I like it and I can do whatever I want when programming in C, but I just hope this isn’t a waste of time
Edit: I’m talking about for software dev
Edit 2: Also I’m in my gap year and I’m trying to learn as much as possible so I can get jobs in first year. Is C a bad idea?
I came up with the following code for aligned_malloc and aligned_free. Referred to a couple of sources online, most of which use a combination of uintptr_t and uint32_t or uint64_t. But isn't it better to use uintptr_t throughout to make the code portable across all machines? The code compiles and runs without any errors, but can you please give me pointers(pun intended) to make it better?
````
void* aligned_malloc(size_t size, size_t alignment){
uintptr_t rv = (uintptr_t) malloc(size + alignment + sizeof(uintptr_t));
if(rv == NULL){
printf("Error allocating memory for aligned_malloc..\n");
exit(1);
}
rv += sizeof(uintptr_t); // to store alignment value
//how much do we need to shift the pointer
uintptr_t offset = alignment - (rv % alignment);
rv += offset;
uintptr_t *storage = (uintptr_t *)(rv - sizeof(uintptr_t));
*storage = offset + sizeof(uintptr_t);
return (void*)rv;
}
void aligned_free(void* ptr){
uintptr_t *offset = (uintptr_t *)ptr - sizeof(uintptr_t);
void *orig = (void *)(ptr - *offset);
free(orig);
}
````
Hello, I'm trying to solve a basic leetcode question in C. The question is `Contains Duplicate`. My problem is that for some reason, the modulo operator is acting weirdly. Here's my code.
As you can see, I also added some print statements to check what was going on.
`│ Value: 927615 | 10007`
`│ Value: 927615 | 10007`
`│ Value: 964607 | 10007`
`│ Value: 964607 | 10007`
`│ Value: 868191 | 10007`
`│ Value: 868191 | 10007`
It should be, 868191
% 10007=
7589. But it's 10007 for some reason.
If anyone understands what I'm doing wrong, I'll be happy to hear it. Thank you!
I thought maybe there is a special character for that but they couldn't find any, so maybe there is a build in library so I could customize the size or something
hello, do you know of a an program or tool that I can simulate the development card and peripherals?
Long story short, with my brother, we are trying to compute all the prime numbers, below 1,000,000. We are doing this on my windows computer.
The thing is that his program (in Perl) compute it without issues, while my program (in c) doesn't work when I put a "#define max 1000000".
The thing is, it works when I put a number smaller, and it also works on my other computer (using Debian, I even could try 100,000,000 it has worked.)
So I am wondering what's wrong? Does Windows has limitations when the values are too big? But if so, why on C and not in other programming languages (such as Perl)?
NOTE : I know Windows is crap, especially for programming, but it's not the point.
Hey everyone i’m in my second year of engineering school in france and since the first the first year we were taught how to programme in C and before that i had 0 experience programming but here’s the probleme i’ve reached a point where i understand all programs when i read them but i dont know how to write them myself and when i look at the correction i understand it immediately did anyone else struggle with that also if so how did you guys overcome that probleme and thanks
Hey, so I'm trying to deepen my knowledge in C by reading and trying out code that is in book: Art of Exploitation 2nd edition and I'm currently at game_of_chance.c (code is on someone's GitHub) and when I tried to remake the code, everytime I try to run it it always says I need to register even tho in the code there are 2 functions that handle the current user's uid and uid that is stored in a file, I traced the problem using gdb and I found that in those functions it seems to work just fine, but it writes to that file the uid of 1000 becomes 256000, so the problem the writing itself I guess? when I tried to print each uid it worked
Hi everyone! Can someone see here why is my do while loop not going to the beginning of the loop? When the user inputs a number outside of the range it outputs the error and just continues on with the next input.
for (int i=0; i<5; i++)
{ int counter;
do
{
counter=0;
printf("Please enter the amount of votes for candidate %d ! (1 to 1000)\n", i+1);
scanf("%i", &c[i].votes);
if (votes<1 || votes>1000)
{
printf("[Error] This input is out of bounds!\n");
counter = 1;
break;
}
} while(counter);
}
}
return 0;
can you replace default preprocessor?
I'm kind of confused cause preprocessor is not a seperate executable, but you can do `gcc -E` to stop after the preprocessing stage, so its kind of seperate sequence of instructions from main compilation, so my logic is that maybe you can replace that?
For my output, if whenever I input "a6Bc D3! F?." it won't print "All characters appear once" and instead just prints "The most occurring character is: " and is just left blank. What do I do to fix it without changing int main() at all? This issue is coming from the function char most_occurring_character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char most_occurring_character ( char *str);
void count_low_up_digit ( char *str, int *lower, int *upper, int *digit);
char * Up_letters ( char *str);
char most_occuring_character ( char *str){
int count[256] = {0};
int max_count = 0;
char most_occur = -1;
for (int i = 0; str[i]; i++) {
count[(unsigned char)str[i]]++;
if (count[(unsigned char)str[i]] > max_count) {
max_count = count[(unsigned char)str[i]];
most_occur = str[i];
}
}
return (max_count > 1) ? most_occur : -1;
}
void count_low_up_digit ( char *str, int *lower, int *upper, int *digit){
*lower = *upper = *digit = 0;
for (int i = 0; str[i]; i++) {
if (str[i] >= 'a' && str[i] <= 'z') (*lower)++;
else if (str[i] >= 'A' && str[i] <= 'Z') (*upper)++;
else if (str[i] >= '0' && str[i] <= '9') (*digit)++;
}
}
char * Up_letters ( char *str){
char *upper_letters = malloc(strlen(str) + 1);
int index = 0;
for (int i = 0; str[i]; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
upper_letters[index++] = str[i];
} else if (str[i] >= 'a' && str[i] <= 'z') {
upper_letters[index++] = str[i] - 32;
}
}
upper_letters[index] = '\0';
for (int i = 0; i < index - 1; i++) {
for (int j = i + 1; j < index; j++) {
if (upper_letters[i] > upper_letters[j]) {
char temp = upper_letters[i];
upper_letters[i] = upper_letters[j];
upper_letters[j] = temp;
}
}
}
return upper_letters;
}
int main() {
char str[50] = "";
char *upper_sorted;
char most_occur = -1;
int lower_case = 0, upper_case = 0, digits = 0;
printf("Enter your string: ");
gets(str);
most_occur = most_occurring_character( str );
if ( most_occur == -1 ) printf("All characters appear once\n");
else printf("The most occurring character is: %c \n", most_occur);
count_low_up_digit( str, &lower_case, &upper_case, &digits );
printf("There is/are %d lower case letter(s)\n", lower_case);
printf("There is/are %d upper case letter(s)\n", upper_case);
printf("There is/are %d digit(s)\n", digits);
upper_sorted = Up_letters( str );
printf("%s\n", upper_sorted);
printf("%s\n", str);
return 0;
}
Hello guys ive started getting into programming today and have been following the tutorial w3schools online C programming course. There is an issue with the output of my code. Code listed below. Some help would really do me good as im hoping to get down to the bottom of this issue ******The output is: ¶▲2 *******
#include <stdio.h>
int main(){
char a = 20, b = 30, c = 50;
printf("%c", a);
printf("%c", b );
printf("%c", c);
return 0;
Hello! I’m a beginner, and I’m learning C right now. Could someone tell me if this code is alright? This is my task: "Create a program that reads a sequence of numbers into an array, finds the maximum and minimum elements, and also outputs their positions/indices in the array. Use a structure to store the value of the element and its position in the array."
#include <stdio.h>#include <conio.h>
struct Element
{
float number;
int index;
};
int main()
{
const int max_size = 50;
struct Element values[max_size];
int size, max_index, min_index;
float max_value, min_value;
do {
printf("Enter the size of the sequence (1-50): ");
scanf("%d", &size);
if (size > max_size || size <= 0)
{ printf("You entered an invalid size!\n"); }
} while (size <= 0 || size > max_size);
for (int i = 0; i < size; i++)
{
if (values[i].number > max_value)
{
max_index = values[i].index;
max_value = values[i].number;
}
if (values[i].number < min_value)
{ min_value = values[i].number;
min_index = values[i].index; }
}
printf("The maximum entered number is %.2f and is at position %d\n", max_value, max_index);
printf("The minimum entered number is %.2f and is at position %d\n", min_value, min_index);
getch();
return 0;
}
Thanks a lot.
How do I get upper_sorted which points to Up_letters to print my input: "a5Bc D9. F.!" to be sorted into upper case letters as "ABCDF"? The output only sorts as BDF.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void count_low_up_digit(char *str, int *lower, int *upper, int *digit)
{
*lower = *upper = *digit = 0;
for (int i = 0; str[i]; i++)
{
if (str[i] >= 'a' && str[i] <= 'z') (*lower)++;
else if (str[i] >= 'A' && str[i] <= 'Z') (*upper)++;
else if (str[i] >= '0' && str[i] <= '9') (*digit)++;
}
}
char *Up_letters(char *str)
{
static char upper[50];
int j = 0;
for (int i = 0; str[i]; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
upper[j++] = str[i];
}
}
upper[j] = '\0';
return upper;
}
int main()
{
char str[50] = "";
char *upper_sorted;
char most_occur = -1;
int lower_case = 0, upper_case = 0, digits = 0;
printf("Enter your string: ");
gets(str);
count_low_up_digit(str, &lower_case, &upper_case, &digits);
printf("There is/are %d lower case letter(s)\n", lower_case);
printf("There is/are %d upper case letter(s)\n", upper_case);
printf("There is/are %d digit(s)\n", digits);
printf("------\n\n");
upper_sorted = Up_letters(str);
printf("%s\n", upper_sorted);
printf("%s\n", str);
return 0;
}
#include <stdio.h>
int main(void)
{
char name[15];
char DOB[9];
char mobile[11];
printf("What is your Name?: ");
fgets (name, 15, stdin);
printf("So your Name is %c?", name);
}
Output: So your Name is �?
The message:-
Threat quarantined
26-10-2024 18:25
Details:
Detected: Trojan:Win32/Bearfoos.A!ml
Status: Quarantined
Quarantined files are in a restricted area where they can't harm your device. They will be removed automatically.
Date: 26-10-2024 18:25
This program is dangerous and executes commands from an attacker.
Affected items:
file: C:\TURBOC3\ashish\classwork\MULTI.exe
The program:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
int A[30][30], B[30][30],M[30][30];
int R,C,n,m,o,p,i;
printf("no.of rows and columns of A:");
scanf("%d %d",&n,&m);
printf("no.of rows and columns of B:");
scanf("%d %d",&o,&p);
if(m!=o){
printf("Multiplication not possible");
}
else{
printf("Enter data in Mat_A:\n");
for(R=0;R<n;R++){
for(C=0;C<m;C++){
printf("\tA[%d][%d]:",R+1,C+1);
scanf("%d",&A[R][C]);
}
}
printf("Enter data in Mat_B:\n");
for(R=0;R<o;R++){
for(C=0;C<p;C++){
printf("\tB[%d][%d]:",R+1,C+1);
scanf("%d",&B[R][C]);
}
}
printf("Product of matrices: \n");
for(R=0;R<n;R++){
for(C=0;C<p;C++){
M[R][C] = 0;
for(i=0;i<m;i++){
M[R][C] += A[R][i]*B[i][C];
}
printf("%d ",M[R][C]);
}
printf("\n");
}
}
return 0;
}
I stumbled upon usage of assembly code inside C programming But not sure when to specific use it Can someone guide me
Say you have a 2D array like so (numbers are arbitrary, they're organised here for examples sake):
int arr[5][5] = {{ 5, 4, 3, 2, 1 },
{ 6, 5, 4, 3, 2 },
{ 7, 6, 5, 4, 3 },
{ 8, 7, 6, 5, 4 },
{ 9, 8, 7, 6, 5 }};
Printing the diagonals from top right to bottom left, the output should be
1,
2, 2
3, 3, 3
4, 4, 4, 4
5, 5, 5, 5, 5
6, 6, 6, 6
7, 7, 7
8, 8
9,
Hopefully the pattern is visible.
How would you implement a function like this without getting index out of bound errors? Struggling on a Project Euler solution. Thanks.
EDIT: the number of cols always equals the number of rows
I know it takes like 50 lines just to pop up a window with "Hello World" written in it. But I love C and I love the Windows GUI. I've tried learning C++ and C# but it's just not fun at all. I think programming is also having fun in writinh. So I've had an idea to make a custom header file that shrinks down the size of the code to make Windows GUI from the lenght of the entire Bible to 3-7 lines. Should I try it or just give up and use C# ?
say I wanted to do something really stupid, that there are probably a dozen better ways to do, but I was really dead set on doing it this way because I'm really stubborn. The idea is to replace the code below with preprocessor directives:
my_array[0] = 0;
my_array[1] = 1;
my_array[2] = 2;
// ...
So, for instance, I could write some code that looks like this:
for (int i = 0; i < ARRAY_SIZE; i++)
{
printf("my_array[%i] = %i;\r", i, i);
}
Then I could copy-paste the output back into my code, but can I do that automatically at compile-time? Yes, I know it's dumb. I just want to know more about preprocessor directives. Maybe in the future, I'll be able to use what I learned to do something useful, maybe not.
To preface, I'm a student in university.
I've been thinking about organization of larger project and I've realized that there's two different ways to create functions for structs. You can have a function inside the struct that has access to the struct members or you can have a global function that you can pass a struct two. Is one of these methods better than the other?
Here's an example for demonstration (sorry for any mistakes I just whipped it together. I'm also not sure how pointers work with structs yet).
struct Example1
{
char d1[5];
char d2[5];
char d3[5];
void print_data()
{
printf("%s\n %s\n %s\n", d1, d2, d3);
}
};
//Example 2
struct Example2
{
char d1[5];
char d2[5];
char d3[5];
};
void print_example_data(Example2* e)
{
printf("%s \n%s \n%s \n", e->d1, e->d2, e->d3);
}
hello everyone . i'm a first year student who just began learning C and systems programming a couple of months ago. After reading on processes and how the operating systems manages them.i'm a person who learns by implementing theory based concepts from scratch so, i decided to work on a project that simulates how processes are managed by the kernel. but due to my skill set , insufficient knowledge and systems programming immaturity, i simulate an individual processes/task with a single thread(for now)
i'm currently still working on it. but i already wrote some of it at least
i know the project might be a really dumb and i apologise. but could i please get a some feed back on it. areas of improvements and whether it is worth it or not . your help would be appreciated a lot . thank you