/r/C_Programming
The subreddit for the C programming language
Click the following link to filter out the chosen topic
comp.lang.c
Frequently Asked Questions/r/C_Programming
Hi !!!!
I’m currently studying for a Computer Science diploma and taking a class called Programming Principles. I missed a few classes and need to catch up during the Christmas break. The final exams are next month, and I really want to smash the assessment. 😅
The assignments are focused on:
NGL, I’m not even sure if I want to stick with C after this class, but I do want to understand it well enough to do well in the finals and figure out if it’s something I want to explore further. Does anyone know any good free courses, tutorials, or YouTube channels to cover these?
Practical, hands-on material would be awesome because I learn better by coding rather than just reading.
Thanks in advance for any recommendations!
на всех сайтов код а куда его вписывать ?
Hallo everyone,
i am currently programming a chat server mainly on linux. I have one PC which runs Windows. So in order to futher work on the project i've installed WSL. But now for some reason the errno constants like ENOMEM are undefined.
Help is appreciated
I have succesully completed the whole code without any error but 1it still isnt showing any otuput :
#include <stdio.h>
int main()
{
int nl,nc,nw,c;
nl = nc = nw = 0;
int in_word = 0;
while((c = getchar()) != EOF)
{
++nc;
if(c == '\n')
{
nl++;
}
if(c == ' ' || c == '\t' || c == '\n')
{
in_word = 0;
}
else if(in_word == 0)
{
in_word = 1;
nw++;
}
// new word logic :
/* we were outside the in_word character ..after that we
encountered a start of the word which results into in_word = 1;
now we are inside the word which will increment the word by 1.
*/
}
printf("nl => %d\nnc => %d\nnw => %d\n", nl, nc, nw);
}
I'm reading Modern C, Jens Gustedt; he talks about 'Abstract State Machine' in his book and I didn't anything about it. Can someone explain it in simple terms?
Note: I'm a novice C programmer.
From what I've seen both Clang and MSVC lack several C features from many different versions, while GCC has almost all of them. This isn't the case with C++ where the three compilers have a very similar amount of features inside their pockets.
This makes me feel like I'm forced to use GCC if I wanna everything in C. Btw, I'm on Windows 10.
I test and experiment with JavaScript in and out of the browser.
In general I try to challenge myself with requirements that are non-trivial.
Fix WontFix
and such. It's a hobby. I get paid to do other stuff, so I'm not beholden
to any team or corporate owners.
I am not a fan of "artificial intelligence". For various reasons I don't think are necessary to go in to in depth here.
Now when I decided to assign myself the task of converting JavaScript to C for cross-compilation to WASM and native executable I thought that some programmer, somewhere must have already achieved that task. Not so much.
There's jsxx, ts2c, compilets, nerd, QuickJS qjsc, porffor, Static Hermes, TypeScript2Cxx, Bytecode Aliiance's Javy, and others.
None of the above really spit out C or C++ that can be easily compile to a native executable
using clang
or gcc
or tinycc
without carrying baggage from the conversion.
That's where random Web sites that claim to use "artificial intelligence", machine learning to achieve the task.
There's a few, one is Convert JavaScript to C using AI.
JavaScript source. An algorithm to calculate the lexicographic permutation of
a set without using recursion. Slightly modified to accomodate various JavaScript
runtimes. We'll name the file test.js
// https://stackoverflow.com/a/34238979
function array_nth_permutation(input, n) {
n = Number(n);
let a = Array.from({ length: Number(input) }, (_, i) => i);
let lex = n;
let b = Array(); // copy of the set a.slice()
for (let x = 0; x < a.length; x++) {
b[x] = a[x];
}
let len = a.length; // length of the set
const res = Array(); // return value, undefined
let i = 1;
let f = 1;
// compute f = factorial(len)
for (; i <= len; i++) {
f *= i;
}
let fac = f;
// if the permutation number is within range
if (n >= 0 && n < f) {
// start with the empty set, loop for len elements
// let result_len = 0;
for (; len > 0; len--) {
// determine the next element:
// there are f/len subsets for each possible element,
f /= len;
// a simple division gives the leading element index
i = (n - n % f) / f; // Math.floor(n / f);
// alternately: i = (n - n % f) / f;
// res[(result_len)++] = b[i];
// for (let j = i; j < len; j++) {
// b[j] = b[j + 1]; // shift elements left
// }
res.push(b.splice(i, 1)[0]);
// reduce n for the remaining subset:
// compute the remainder of the above division
n %= f;
// extract the i-th element from b and push it at the end of res
}
return `${lex} of ${fac - 1} (0-indexed, factorial ${fac}) => ${
JSON.stringify(res)
}`;
} else {
if (n === 0) {
return `${JSON.stringify(res)}\n`;
}
return `${n} >= 0 && ${n} < ${f}: ${n >= 0 && n < f}`;
}
}
console.log(array_nth_permutation("4", "5"));
Pasting the above JavaScript into the above Web site results in this C code in a few seconds
// This code snippet is a JavaScript to C translation of a function that calculates the nth permutation of an array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* array_nth_permutation(const char* input, const char* n_str) {
int n = atoi(n_str);
int length = atoi(input);
int* array = (int*)malloc(length * sizeof(int));
int* b = (int*)malloc(length * sizeof(int)); // copy of the set array
int lex = n;
int result_length = 0;
int factorial = 1;
for (int i = 0; i < length; i++) {
array[i] = i;
b[i] = i;
}
// compute factorial
for (int i = 1; i <= length; i++) {
factorial *= i;
}
int fac = factorial;
int* res = (int*)malloc(length * sizeof(int)); // return value
// if the permutation number is within range
if (n >= 0 && n < factorial) {
// start with the empty set, loop for length elements
for (; length > 0; length--) {
factorial /= length;
// a simple division gives the leading element index
int i = (n - n % factorial) / factorial;
res[result_length++] = b[i];
// reduce n for the remaining subset:
n %= factorial;
// extract the i-th element from b and shift elements left
for (int j = i; j < length - 1; j++) {
b[j] = b[j + 1]; // shift elements left
}
}
// Prepare the result string
char* result = (char*)malloc(256); // allocate enough space for the result
sprintf(result, "%d of %d (0-indexed, factorial %d) => [", lex, fac - 1, fac);
for (int i = 0; i < result_length; i++) {
char buffer[10];
sprintf(buffer, "%d", res[i]);
strcat(result, buffer);
if (i < result_length - 1) {
strcat(result, ", ");
}
}
strcat(result, "]");
free(array);
free(b);
free(res);
return result;
} else {
char* result = (char*)malloc(100);
if (n == 0) {
sprintf(result, "[]\n");
} else {
sprintf(result, "%d >= 0 && %d < %d: %d", n, n, factorial, (n >= 0 && n < factorial));
}
free(array);
free(b);
free(res);
return result;
}
}
int main() {
char* result = array_nth_permutation("4", "5");
printf("%s\n", result);
free(result);
return 0;
}
Modifying the main
function to support passing arguments
int main(int argc, char *argv[]) {
char* result = array_nth_permutation(argv[1], argv[2]);
printf("%s\n", result);
free(result);
return 0;
}
clang
to see if we have close to 1:1 input and outputllvm-project/build/bin/clang test.c -o test
./test 9 362879
362879 of 362879 (0-indexed, factorial 362880) => [8, 7, 6, 5, 4, 3, 2, 1, 0]
Cool, that works. I don't really have guilt in the things I do. Using "AI" after writing on programming boards that "AI" means Allen Iverson, now using a random Web site that says it uses "AI" to produce the expected result doesn't quite sit right with me. Am I cheating?
Well, we had better cheat if we are gonna cheat and do the whole loop.
wasi-sdk/bin/clang test.c --sysroot=wasi-sdk/share/wasi-sysroot -o test.wasm
wasmtime run test.wasm 9 362879
362879 of 362879 (0-indexed, factorial 362880) => [8, 7, 6, 5, 4, 3, 2, 1, 0]
That works, too.
binaryen/bin/wasm2js test.wasm -o test.wasm.js
Modify the resulting asm.js format slightly, using a minimal WASI runtime that does not define filesystem access wasi-minimal.js, some parts redacted for brevity
// import * as wasi_snapshot_preview1 from 'wasi_snapshot_preview1';
import process from "node:process";
import { WASI } from "./wasi-minimal.js";
import * as fs from "node:fs";
// ...
var memasmFunc = new ArrayBuffer(0);
var args = await (async() => {
var xargs = process.argv.slice(-2);
var bool = xargs.map(Number).some((n) => Number.isNaN(n));
if (bool) {
for await (const data of process.stdin) {
var ret = new TextDecoder().decode(data).trim().split(" ");
ret.unshift(" ");
return ret;
}
}
xargs.unshift(" ");
return xargs;
})();
let wasi = new WASI({
env: {},
args,
fds: [
{
type: 2,
handle: fs,
},
{
type: 2,
handle: fs,
},
{
type: 2,
handle: fs,
},
],
});
var retasmFunc = asmFunc({
"wasi_snapshot_preview1": wasi.exports,
memory: { buffer: memasmFunc }
});
export var memory = retasmFunc.memory;
wasi.memory = memory;
export var _start = retasmFunc._start;
_start();
echo '9 362879' | node --no-warnings test.wasm.js
362879 of 362879 (0-indexed, factorial 362880) => [8, 7, 6, 5, 4, 3, 2, 1, 0]
echo '9 362879' | deno test.wasm.js
362879 of 362879 (0-indexed, factorial 362880) => [8, 7, 6, 5, 4, 3, 2, 1, 0]
echo '9 362879' | bun run test.wasm.js
362879 of 362879 (0-indexed, factorial 362880) => [8, 7, 6, 5, 4, 3, 2, 1, 0]
Full circle of cross-compilation complete.
Of course, the question about whether I'm cheating in programming or not by using a random Web site to convert JavaScript to C is rhetorical, for the most part.
Of course I'm cheating. A seasoned C programmer might probably say something like "There's no error checking!". "And Just learn C!".
A seasoned JavaScript programmer might say something like "Why are you doing that? And by the way, why the heresy of using node and deno and bun at the same time!". That's it. You need to be downvoted into absolute oblivion and banned, too.
Keep asking questions to see if one of these JavaScript engine/runtime projects can achieve the conversion using FOSS outside of an unobservable box that makes request to a remote Web site that doesn't disclose source code.
For sport. Because it's challenging. Clearly hasn't been done in a single application. React and TypeScript and Next.js are boring...
I heard somebody say that on the Jim Rome show years ago. I tried to do this edge case conversion without "AI".
GitHub said I have access to their Copilot... For free. 'Cause I certainly didn't ask for that feature, and ain't gonna pay for it. I read somewhere during this project that Copilot can convert source code to source code.
I can't do it. I've cheated enough...
But is it really cheating? Damn I despise even the thought of being a hypocrite.
Get me off the "AI" teat. Even though I only took a sip of the Kool-Aide... and don't plan on taking a shot.
Yeah, I'm kind of thinking about this more than I even considered possible.
Where's FOSS when you need it!
I don't want to be complicit in ushering in Skynet!
The horror...
So basic I have this project that I need to do and am kind of stuck on the board element part. I really need help understanding the logic behind it because the reason being is that I am an idiot
Board Elements
There are ten game elements. Each has a 1/10 probability of occurrence. The game elements are given below. (Each X represents 0 or 1, randomly generated)
and it goes like this
Number of squares
in game piece
Pieces
1,X
2,XX
X
X,
3
XXX,
X
X
X,
XX
X,
this is L shaped
XX
X,
this is L shaped
X
XX,
this is L shaped
X
XX,
this is L shaped
4.XX
XX The X is 2*2
They should be in this pattern don't ask me why I did this the sub doesn't allow pictures
any help would be appreciated
// useless example struct
typedef struct {
int x;
} SomeStruct;
// make 2d array of ints
int **arr_a = malloc(10 * sizeof(*arr_a));
for (int i = 0; i < 10; i++) {
arr_a[i] = malloc(10 * sizeof(**arr_a));
}
// make 2d array of SomeStructs
SomeStruct **arr_b = malloc(10 * sizeof(*arr_b));
for (int i = 0; i < 10; i++) {
arr_b[i] = malloc(10 * sizeof(**arr_b));
}
(in the example it is a hardcoded length of 10, but in reality it is of course not hardcoded)
In the first case, the **arr_a, the language server doesn't warn me.
In the second case, **arr_b, it warns me "Suspicious usage of sizeof(A*)".
is the way I'm doing it not idiomatic? is there a better way to dynamically allocate a 2d array?
just trying to learn. it seems to work fine.
In C23's grammar, the balanced-token
rule leads to a syntax which allows nested arguments of arbitrary depth (potentially infinite!). Why is that? Is there any reason to allow more one one level of depth? See page 470 of the standard.
(6.7.13.2) attribute-specifier:
[ [ attribute-list ] ]
(6.7.13.2) attribute-list:
attributeopt
attribute-list , attributeopt
(6.7.13.2) attribute:
attribute-token attribute-argument-clauseopt
(6.7.13.2) attribute-token:
standard-attribute
attribute-prefixed-token
(6.7.13.2) standard-attribute:
identifier
(6.7.13.2) attribute-prefixed-token:
attribute-prefix :: identifier
(6.7.13.2) attribute-prefix:
identifier
(6.7.13.2) attribute-argument-clause:
( balanced-token-sequenceopt )
(6.7.13.2) balanced-token-sequence:
balanced-token
balanced-token-sequence balanced-token
(6.7.13.2) balanced-token:
( balanced-token-sequenceopt )
[ balanced-token-sequenceopt ]
{ balanced-token-sequenceopt }
any token other than a parenthesis, a bracket, or a brace
So today I made my first calculator basically at first I was learning about the old topics like datatypes there are around 32 datatypes like integers , float, character and character and many more so I learned these three today. What I did was how memory concepts work I now can build memory so easily just have to give name of memory if I have to access something from computer, they don't have brain like us that they can remember but what we have to do is give them a memory that they can know to display for it like I want my computer to show number 2 if I hit any keyword it will if I write it like integer then the name of memory then just have to put the integers and we can can't put other number instead of int otherwise it will still work for float but won't with any other characters. Then same with float and character. Also if I want to store data in form of integer I can store upto 4bytes and the total no. Of numbers I can store is 2^32 if I'm using 32bit software and thats what I did and if for 2^64 for 64 bit software we can multiply this if we want to increase the number of storage. But also, I can use long instead of int both 4bytes and double instead of float , here the bytes double , and character is of 1 byte so I can only store one character in it. So all that wasn't enough I learned then a %i/n thing with this I can change the like of display multiple characters or int or float if I have to print and the printable size is 1024x768 something like that, then after this I did was scanf it's not same as printf but if I need to put value after but not inbuilt and given value from starting it helps us in that scanf work in all database too, all I have to do is scanf the (" necessary") but %i or %d or %f just according to my Variable I want to put inside or someone else uses so if they want to put inside and I also stops that that point also I can add multiple integers without using scanf again and again just by add a space to it, so using scanf I made a basic 2 numbers calculator also area finder it isn't custom yet like I can't find all areas in it but it is all I learned, it was fun tho. I won't learn tommorow and day after Tommorow cuz I have different schedules but will continue on friday maybe cuz. Coding is fire if it's understandable. Tbh. I hope you find a good tutor if you read this and wants to start coding. Anyways good luck for you and goodluck for me too.
Hey, first time posting here. I'm getting into C23 but the lack of highlighting for sublime text is driving me crazy. Everything compiles and runs and functions just fine otherwise. I'll just feel a deep sadness in my heart if the little letters on my screen aren't colorful enough.
I looked around ST's package control and did several searches but found no support for C23 syntax and was curious if anyone happened to have a custom sublime syntax file for it, or knew where I could get one.
i have a bash script that creates a process then detaches it from my script to run as daemon and i want to use a c program when i send the pid of the process it modifies the handler of SIGTERM for example is it possible?
A hardware manufacturer includes a .dll file with their machine, which is used by a GUI program. However no header files or lib files are included. There is however some documentation about the functions used in the .dll file.
I am wondering, is it possible to call the functions from the dll file in a C program? If so, how would I go about this? Thanks!
I need help.
Full disclosure, this is for the TSENS (temperature sensing) peripheral on the die of a Microchip ATSAMC21J18A microcontroller.
I have a tsens_periph_t
register map, and within it are three problematic registers:
typedef union
{
uint32_t raw;
struct __attribute__((packed)) {
uint32_t n_value :24;
int :8;
};
} tsens_gain_reg_t;
typedef union
{
uint32_t raw;
struct __attribute__((packed)) {
int32_t n_value :24;
int :8;
};
} tsens_offset_reg_t;
typedef union
{
uint32_t raw;
struct __attribute__((packed)) {
uint8_t freq :6;
int :2;
uint8_t temp :6;
int :18;
};
} tsens_calib_reg_t;
typedef struct __attribute__((packed))
{
//...
volatile tsens_gain_reg_t gain;
volatile tsens_offset_reg_t offset_corr;
volatile tsens_calib_reg_t calib;
//...
} tsens_periph_t;
Those three registers in particular need to be initialized with values stored in Flash, a space I've called NVM_TSENS_CALIB
. To get the job done, I wrote:
void tsens_calibrate (volatile tsens_periph_t self[static 1], error_t * p_error);
and in there, this is the code that should, by all logic and reasoning work:
self->gain.n_value = NVM_TSENS_CALIB->gain;
self->offset_corr.n_value = NVM_TSENS_CALIB->offset;
self->calib.freq = NVM_TSENS_CALIB->freq;
self->calib.temp = NVM_TSENS_CALIB->temp;
But it doesn't. I turn around and do:
if ((NVM_TSENS_CALIB->gain != self->gain.n_value)
|| (NVM_TSENS_CALIB->offset!= self->offset_corr.n_value)
|| (NVM_TSENS_CALIB->freq != self->calib.freq)
|| (NVM_TSENS_CALIB->temp != self->calib.temp))
{
THROW_ERROR(TSENS_ERROR_FAILURE_TO_CALIBRATE);
}
And that's hitting the error code every single time. My error reporting is kinda like a little brother to an exception model. So, I changed the above assignment code to this:
uint32_t buffer;
uint32_t * p_buffer;
buffer = NVM_TSENS_CALIB->gain;
printf("NVM_TSENS_CALIB->gain: 0x%.08lX\r\n", buffer);
p_buffer = (uint32_t *)&(self->gain);
printf("&(self->gain): %p, p_buffer: %p\r\n", &(self->gain), p_buffer);
*p_buffer = buffer;
printf("TSENS->gain.raw: 0x%.08lX\r\n", self->gain.raw);
self->gain.n_value = buffer;
printf("TSENS->gain.raw: 0x%.08lX\r\n", self->gain.raw);
buffer = NVM_TSENS_CALIB->offset;
printf("NVM_TSENS_CALIB->offset: 0x%.08lX\r\n", buffer);
p_buffer = (uint32_t *)&(self->offset_corr);
printf("&(self->offset_corr): %p, p_buffer: %p\r\n", &(self->offset_corr), p_buffer);
*p_buffer = buffer;
printf("TSENS->offset_corr.raw: 0x%.08lX\r\n", self->offset_corr.raw);
self->offset_corr.n_value = buffer;
printf("TSENS->offset_corr.raw: 0x%.08lX\r\n", self->offset_corr.raw);
uint8_t freq = NVM_TSENS_CALIB->freq;
uint8_t temp = NVM_TSENS_CALIB->temp;
printf("NVM_TSENS_CALIB->freq: 0x%.02X\r\n", freq);
printf("NVM_TSENS_CALIB->temp: 0x%.02X\r\n", temp);
buffer = ((temp & 0x3F) << 8) | (freq & 0x3F);
printf("buffer: 0x%.08lX\r\n", buffer);
p_buffer = (uint32_t *)&(self->calib);
printf("&(self->calib): %p, p_buffer: %p\r\n", &(self->calib), p_buffer);
*p_buffer = buffer;
printf("TSENS->calib.raw: 0x%.08lX\r\n", self->calib.raw);
self->calib.freq = freq;
self->calib.temp = temp;
printf("TSENS->calib.raw: 0x%.08lX\r\n", self->calib.raw);
and here's it's output:
NVM_TSENS_CALIB->gain: 0x000167CE
&(self->gain): 0x40003018, p_buffer: 0x40003018
TSENS->gain.raw: 0x000167CE
TSENS->gain.raw: 0x00010101
NVM_TSENS_CALIB->offset: 0x00002853
&(self->offset_corr): 0x4000301c, p_buffer: 0x4000301c
TSENS->offset_corr.raw: 0x00002853
TSENS->offset_corr.raw: 0x00000000
NVM_TSENS_CALIB->freq: 0x2A
NVM_TSENS_CALIB->temp: 0x1F
buffer: 0x00001F2A
&(self->calib): 0x40003020, p_buffer: 0x40003020
TSENS->calib.raw: 0x00001F2A
TSENS->calib.raw: 0x00001F1F
TSENS Error: Failure to Calibrate
So, let's take stock. Pulling the individual field values out of NVM_TSENS_CALIB
, not a problem. The addresses of the individual registers relative to the self
pointer, not a problem. Going medieval and just slamming a uint32_t
value into a naked pointer to such, not a problem. In fact, when I'm not using any of the old code, and just using the *p_buffer = buffer;
to store the calibration values into all of the registers, that same symbolic naming path syntax, when used to pull the values back out, not a problem.
It's just in the packed bit-field struct member assignment statements that there's a problem.
Why? Taking all suggestions, because I'm out of options. This same kind of symbolic naming path syntax is working everywhere else within tsens_periph_t
, and in register map overlays for dozens of different peripherals. Why are these three registers giving me fits? And only on assignment, not referencing into them.
What is a good book to learn advanced C programming and learning in depth about the system as well?
Hi everyone ,I am in my 1st year ,Bca and 2nd semster . I starte solving the book called the c prograamming language by Dennis ritchie and Brian W. Kernighan . MY main objective was to do the book for logic development and problem solving but after starting this book i believed to be cooked very badly as the questions are extremely different then what i learn till now . I asked for advice from various professors and looked at redditor 's views on this where many of them mentioned different books ,many said that why people are even solving books in c
My professor told me to do the book named balaguruswami(an indian book)which is beginner friendly .Can anyone just tell me what shall i do like shall i only solve the most common questions and jump to new language or shalll i dive deeper into c language .i dont have any idea what to do.
I've tried my hand at hand-rolled GC before. I made this for my shell --- which I doubt will be reusing again --- and I made this Perl script which based on preprocessor-directive-like notation will preprocess your file and add a mark & sweep heap to it.
But notice that --- although both of these do sweep, they still sweep based on reference counting:
1- There's a heap; 2- There's a memory object with a reference count; 3- You can increase and decrease the reference count; 4- During a heap sweep, if reference count is 0, the memory object is marked and the swept.
But I do know that is not how real GC libraries like libgc do it! I have read The Hadbook of Garbage Collection and it failed to mention just how to find live references in the heap? As in, how to traverse the heap and count for live objects?
Of course you need to keep tabs of all the pointers in a heap-like object. But do you have to traverse the whole heap? Even if the heap is like 50 gigabytes of data?
Also, how do you gain access to the heap? I know Linux has 3 variables which mark the start and end of the heap --- and I've forgotten what these variables are. But it's not very portable is it.
Thanks.
I would love to become better at C Programming. I'm an absolute beginner to programming. But I'm willing to spend 2 to 3 hours everyday for at least next one year, please help/guide me in the right direction. Books, tutorials, online courses, coding tools, related topics to understand C more clearly, anything that makes me confident in C. Thanks in advance.
so this programme seems quite ironical and confusing as it asks for writing a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
Here : i have seen the code and tried to understand it but it shows the branching of conditional statements in a very confusing manner
#include <stdio.h>
int main() {
int c; // Variable to store each character
int inBlank = 0; // Flag to track if the previous character was a blank
// Loop to read each character until EOF
while ((c = getchar()) != EOF) {
// If the current character is a blank space
if (c == ' ') {
// Only print a blank if the previous character wasn't a blank
if (!inBlank) {
putchar(' '); // Print one blank
inBlank = 1; // Set flag to indicate the previous character was a blank
}
} else {
// For any non-blank character, just print it
putchar(c);
inBlank = 0; // Reset the flag because it's no longer a blank
}
}
return 0;
}
Hello all,
I'm a bored 10-year web developer. Web is good for making money (especially if you come from the third world like me), but after creating buttons, modals, and UI effects that only designers and devs care about, I decided to make some changes. I always prefer low-level but I was sold by money to the web.
Recently I started my master's in distributed systems, but I'm also doing in my free time some other universities courses. I like the university course style, so right now I'm doing the following:
Computer Architecture ETH Zurich
CMU - Advanced Database Systems
What other courses you guys suggests?
LEVEL* level_create(FILE* fd)
{
if (fd == NULL) return NULL;
LEVEL* level = (LEVEL*)malloc(sizeof(LEVEL));
if (level == NULL) return NULL;
level->srow = 0;
level->scol = 0;
level->next = NULL;
level->prev = NULL;
level->level_steps = 0;
char pole[81];
int i, j;
int cols = 0, rows = 0;
if(fscanf(fd,"%29[^;]%*c", level->info.name) != 1) {
printf("Error: Failed to read name.");
free(level);
return NULL;
}
if(fscanf(fd,"%29[^;]%*c", level->info.password) != 1) {
printf("Error: Failed to read password.");
free(level);
return NULL;
}
if(fscanf(fd,"%49[^;]%*c", level->info.description) != 1) {
printf("Error: Failed to read description.");
free(level);
return NULL;
}
`for(i = 0; i < level->info.nrows; i++){`
if(fgets(pole, sizeof(pole), fd) == NULL){
free(level);
`printf("error with rows %d",i);`
return NULL;
}
`pole[strcspn(pole, "\n")] = '\0';`
if(strlen(pole) != level->info.ncols){
free(level);
`printf("error with lenght of rows in row %d",i);`
return NULL;
}
`cols = strlen(pole);`
for(j = 0; j < level; j++){
switch (pole[j]){
case ' ':
level->map[i][j] = EMPTY;
break;
case '#':
level->map[i][j] = WALL;
break;
case '$':
level->map[i][j] = BOX;
break;
case '@':
level->map[i][j] = SOKOBAN;
level->srow = i;
level->scol = j;
break;
case '.':
level->map[i][j] = PLACE;
break;
case '*':
level->map[i][j] = BOX_ON_PLACE;
break;
case '+':
level->map[i][j] = SOK_ON_PLACE;
level->srow = i;
level->scol = j;
break;
default:
free(level);
printf("error vo switchy");
return NULL;
}
}
`rows++;`
}
`level->info.nrows = rows;`
`level->info.ncols = cols;`
if(level->srow == -1 || level->scol == -1){
free(level);
`printf("error in sok %d %d ",level->srow, level->scol);`
return NULL;
}
return level;
}
So data of one level looks like this houston;harvey;we got a problem;-----#####-----------|-----#---#-----------|-----#$--#-----------|---###--$##----------|---#--$-$-#----------|-###-#-##-#---######-|-#---#-##-#####--..#-|-#-$--$----------..#-|-#####-###-#@##--..#-|-----#-----#########-|-----#######--------- where you need to parse name, pass, desc., this is easy. The hard part comes for me in level data parsing... I managed to get it to work, but there is always only one row, meaning level should have lets say 3 rows but it only has one. If anyone is interested in helping me i would really apreaticate it :D
Hi Guys, I have experience in python and ardiuno programming, but I want to use C for everyday use like I did with python any project ideas to practice and resources ?
So i tackled this question where i tried to understand it but rather than that i simply remembered it (unintentionally),is there anyone who could explain me how this code works . Efforts will be appreciated , This is a programme which counts the number of characters inputted but it gives an extrsa incremented value on the final output
#include <stdio.h>
int main()
{
int numb;
numb = 0;
while(getchar() != EOF)
{
numb++;
printf("the numb is %d\n",numb);
}
}
Today is the day I started learning c programming and the things I learned , assures me a best programming language is c C Lang was made back in 1976 in bell lab by just a single person , Sir Dennis ritcher (RIP) . He was building it for Linux software but got into programming language people makes app with it. It is a platform dependent means if I downloaded the software to run 'c' in windows then it only runs in windows no mac or Linux and vice versa for other operating system. Also the same lab but different person to create c++ the first name given by sir bjarne, was he used to call it c with classes after that he calls it c++, btw back to topic I learned there are 3 software for running c Lang also you can't run c in notepad it needs a compiler that's why so me personally using codeblocks it is so friendly tbh. And two more. So finally what I learned in c Lang today is main() { "that's where we put code" } It looks like that I don't have nice picture of it but you'll get the idea if you use codeblocks. And everybody knows printf but what I learn is getch(); to stop the screen to close or the program we wrote ends at getch(); otherwise will run but won't be able to see cuz it's c Lang is so fast. And also build and run we can use it too to run our program. That's what I learned I will comeback next to tell what I learned
Hello, fellow C enthusiasts! I'm excited to announce the release of TidesDB v0.3.0 BETA. TidesDB is an open-source, durable, transactional, and embedded storage engine. It is a shared C library designed and built from the ground up, based on a log-structured merge tree architecture. I started TidesDB as a passion project because I absolutely adore databases and everything related to storage. The goal of TidesDB is to create the simplest, easiest-to-use, and fastest storage engine.
Here are some current features!
I've spent lots of time thinking about how to approach the API and am truly happy with it. I'd love to hear your thoughts on this release and generally the code. I've been writing code for 17 years, C on and off for that time. Just recently I am writing C everyday.
Thank you for checking out my post :)
Hey,
I’m trying to set up a GitHub Workflow to check all the .c files in my repository for memory leaks and other issues using Valgrind. Unfortunately, I couldn’t get it to work since I’m relatively new to both C programming and writing .yml configuration files. I was wondering if anyone could help me out or share a general Valgrind workflow setup—or even point me to repositories that already use such workflows. Any help would be greatly appreciated!