1
12
submitted 2 years ago* (last edited 2 years ago) by JaumeI@programming.dev to c/learn_programming@programming.dev

This community is aimed at two specific topics:

  • Support general programming questions, of any language, mainly for people beginning their journey in programming.
  • Give some advice on programming education or career.

What this community doesn't intend to do:

  • Give specific answers to very specific, non-beginners, problems of a particular language. You probably can go to a community of that language to get help with that.
  • Solve your programming assignments. You can ask for a specific issue, but it's essential that you learn to think and solve them, or you'll never progress.

As suggested by Captain Janeway, here are some rules specific to the posts:

  • Paste your code. Unless there's not any other way, please don't provide screenshots of the code, it's harder to review.
  • If possible, try to provide a runnable example of the code in question
  • Explain as much as you can: what you’ve tried, what the error is, what you think the problem is
  • As usual, be kind

The probability of getting an answer will increase dramatically if you follow these points.

This post will be updated periodically, with any new inputs considered necessary.-----

2
29

Some terminal applications are positively deluxe. Completely decked out. Here are some examples (these are all screenshots from my terminal emulator):

!

So my question is: how do I design a terminal application to look like that?

3
6

cross-posted from: https://sopuli.xyz/post/45002077

If this isn't the right community for this post, let me know and I'll move it somewhere else.

I'm working my way through nandgame, and I'm stuck on the "call" macro in the function calls section of the stack machine unit. These are the instructions:

I was stuck on it for a while, so I looked up the solution and am going off the one given here (it's the only one I could find).

So far, I haven't gotten it to work. At first, it was giving me syntax errors because the labels weren't defined, so I replaced A = [LABEL] with label [LABEL] followed by A = [CONST], according to the specified calling convention. It also gave me a similar syntax error for TEMP_ADDR, which is never specified in the instructions, so I assigned it 0x7f00. So here is what I end up with (all in Assembly):

(note: the stack pointer, SP, is defined by a shared constant SP = 0)

Test code:

init.stack
call functionName 0
stop

function FunctionName 0
push.value x42
return

Macro: call

# Assembler code
## Push the current ARGS and LOCALS on the stack
push.static ARGS
push.static LOCALS

## Push the return address.
push.value after

## Set ARGS to point to the start of the arguments
A = SP
D = *A
A = argumentCount
D = D - A
A = 3
D = D - A
label ARGS
A = 1
*A = D

## Jump to functionName.
goto functionName

## Set return address:
label after

## Restore ARGS and LOCALS from the stack
A = ARGS
D = *A
label TEMP_ADDR
A = 0x7f00
*A = D
pop.D
label LOCALS
A = 2
*A = D
pop.D
A = ARGS
*A = D

## Push RETVAL.
label RETVAL
A = 6
D = *A
push.D

Macro: function

# Assembler code
## Define a label functionName
label functionName

## Set LOCALS to the current SP
A = SP
D = *A
label LOCALS
A = 2
*A = D

## Advance SP by localsCount
A = localsCount
D = A
A = SP
D = D + *A
*A = D

Macro: return

# Assembler Code
## Pop the top value into RETVAL
pop.D
label RETVAL
A = 6
*A = D

## Set SP to LOCALS
label LOCALS
A = 2
D = *A
A = SP
*A = D

# Pop the return address and jump to it
pop.D
A = D
JMP

Note: functionName, argumentsCount, and localsCount are all listed as placeholders above the relevant macro, but it doesn't describe how to define these. I'm guessing that comes in a later unit. The code block for the call macro gives me a red bar for each line with a placeholder, but this doesn't happen for the function macro which also includes placeholders. In any case, this doesn't seem to get in the way of the program as it still runs smoothly.

So as it is, when I run it, everything seems to work as intended. This is the result when it reaches the stop macro (infinite loop):

Which looks like it's doing everything it's supposed to do. But when I click "Check solution", this is what it says:

("Expected SP (RAM address 0) to be hex 101. (Was 104)")

Which is strange, because in the computer section you can clearly see that the SP content is hex 0101. So I don't know what's going wrong.

I stepped through the program tick by tick, and the only place SP ever reaches 104 is after the function macro, when it runs push.value x42, after which it runs the return macro which begins with pop.D, reducing SP back to 103.

Could it be the evaluator is assessing the value of SP at the end of the code block, instead of where it runs the stop macro? So perhaps I could try replacing stop with a jump to the end, followed by stop... Now that I think of that, I think it might work. I'm still going to post this though, because I already went through all the trouble. And in case it doesn't work, if anyone else has any ideas please share them!

I can expand the rest of the macros if need be, but they already passed the evaluation so they're all working according to specs.

Thanks in advance!

Edit:

I thought for sure that would work. I changed the test code block to this:

init.stack
call functionName 0
A = end
JMP

function FunctionName 0
push.value x42
return
label end
stop

The program runs exactly as it's supposed to, except now the stop loop is at the end of the code. The computer output still looks the same, except now the program counter loops between 60 and 61 at the end (as expected). But the evaluator is still giving me the same error! I'm stumped...

Edit 2: added annotations to code blocks to make it easier to read

4
11

I often forget to push a few things depending on how Git decides to label my work. Today it labeled a move as a file deletion and add, and only the deletion is present on the upstream, and now the upstream doesn't even compile properly. And I don't want to pull out my hair to resolve yet another conflict, because the only help with Git I can get is jUsT reAD ThE WhoLE maNUaL.

One other thing is that I refuse to use VSCode, especially since they're pushing AI slop code generation so much, and I use KATE instead.

5
5
termux help (sh.itjust.works)
submitted 1 week ago* (last edited 1 week ago) by maya_the_good_apple@sh.itjust.works to c/learn_programming@programming.dev

Is there a manual for termux? I have no idea what each command does

6
1
submitted 1 week ago* (last edited 1 week ago) by rockSlayer to c/learn_programming@programming.dev

I'm working on a bash script that navigates through a cloud path, and I'm getting the error -bash: [[: gs://: syntax error in expression (error token is "://")

To me, this indicates that bash is attempting to evaluate the variable instead of comparing strings, but I have no clue why that would be the case.

This is the relevant code:

GSPATH='gs://'
if [[ "$GSPATH" -eq 'gs://' ]]; then
    echo 'empty'
7
3
submitted 1 week ago* (last edited 1 week ago) by rockSlayer to c/learn_programming@programming.dev

I need to create a table with summary statistics on a data frame, and I want to group 4 similar columns (N_cases, percent) into 2 broader columns (incident, prevalent), so it would look like this:

| Prevalent | Incident |
|    N | %  |   N | %  |
8
3

I originally asked this question on The Microchip Forums

I recently installed the MIPS QEMU emulator and tried implementing a simple function that hammers a character to the screen

#define UART_BASE 0x1F000900
#define UART_LSR 0x00000030


void print_char(char c)
{
    for(int i=0; i<1; i--)
    {
        *(volatile char *)(UART_BASE) = c;
    };
}

I thought maybe my UART address was incorrect, but according to the MIPS Malta manual I'm on the right track. I called the function here in src/init.c

extern void clear_bss(void);
extern void print_char(char);

void
init(void)
{
    char letter = 'h';
    clear_bss();
    print_char(letter);
    return;
}

My linker script seems fine as well

MEMORY
{
    ram (rwx) : ORIGIN = (0x8+0x01000000), LENGTH = 128M
    flash (rx) : ORIGIN = 0xbfc00000, LENGTH = 4M
}

SECTIONS
{
    .text : ALIGN(4)
    {
        KEEP(*(.ivt))
        *(.text*)
        . = ALIGN(4);
        _etext = .;
    }>flash


    .bss : ALIGN(4)
    {
        __bss_start = .;
        *(.bss)
        *(COMMON)
        __bss_end = .;
    }>ram
}

_stack = ORIGIN(ram)+LENGTH(ram)

After compilation I stripped the ELF headers and padded the binary to 4 megabytes. I then tried running it using qemu-system-mips -pflash bin/boot.bin -nographic -M malta

It compiles just fine. QEMU seemingly runs it just fine (minus a warning on auto-detecting formats.)

I need help figuring out what I'm doing wrong.

Thanks in advance.

9
7

I have a feeling I'm stuck in tutorial hell, and I need to start actually building things. But I don't know where to start :/

Also I'm really bad at syntax. I only know concepts like for loops, while loops, if-elif-elses, etc...

So maybe something that helps me learn more about coding syntax would be helpful.

Thanks!

10
2
How do compilers work? (pvs-studio.com)
11
17

Today I did a git push --force, then I had to create a branch out of the old code, but other times I had to save the files I worked on, delete the local repository, git clone again, then reapply my fixes. I want to at least have a bookmark on how to fix things in the future.

Yes, I've heard about VSCode plugins, that supposed to help. But no, I don't want to use a glorified webpage to do coding, regardless if it's directly tied to Micro$lop, or some of the slop was removed by 3rd parties. I tried KATE once, I cannot go back to some sluggish webpage, which only argument for use at the moment is "but it has plugins".

12
7
13
5

The official repository is for the PipeWire server does not have a separate folder for include files (well, it only contains Valgrind files), and I don't want to skim through a lot of docs to select what needs for audio, then reconstruct it in a text editor.

14
22

Holy shit! It's so easy and accesible. The best part is that it's simpky build in to linux (or wsl). It's just a terminal command "vimtutor".

I'm astonished that nobody has ever told me about this before.

15
6

cross-posted from: https://programming.dev/post/47452240

We’re continuing our webinar series on building your own fictional programming language!

In our first session, we explored the core building blocks: the lexer, parser, semantic analyzer, and evaluator—how they work and how they fit together.

Now it’s time to dive into grammars. What is a language, really? How can you describe it in a way that a program understands what a sequence of symbols means and what result it should produce? We’ll break it down in a clear and practical way—and, of course, get hands-on with grammars.

Join our webinar on March 27, 1:00 PM UTC+1—there will be lots of interesting insights to discover!

16
4

All the tutorials I can find is just telling me to jUSt UsE tHe DefAUltS (or even to use SDL or some similar library instead of my own solution), but some more advanced features such as getting HD rumble working on controllers with such features would require to connect to select devices.

So far I've tried:

  • using library functions, but they give weird results for some reason.
  • reading the contents of /proc/asound/cards, which supposed to work and contains some very useful addresses, but not the PCM handles themselves.

Unfortunately, 99% of my search results is about how to configure ALSA to be used in Linux, which is obviously not what I need.

17
5

I know I have to add my projects and make the lists more visually appealing. But I am getting lazy reading books :P

18
16
submitted 1 month ago* (last edited 1 month ago) by emotional_soup_88@programming.dev to c/learn_programming@programming.dev

I saw one example

int x = 10;
int y = 5;

bool isGreater = x > y;

printf("%d", isGreater);

But I could write this

int x = 10;
int y = 5;

printf("%d", x > y);

I am a complete beginner and I have no real reason why I would or would not want to deal with boolean variables, but I want to understand their raison d'être.

Edit: typo city

19
4

There's this snd_pcm_open() function, and one of its arguments takes "ASCII identifier of the PCM handle". How can I get it for each individual devices?

20
10

I have been learning Java through the Java MOOC and I find the workbook-style approach of learning very effective for me. Basically, I'm looking for resources, offline or online that have plenty of exercises.

Preferably, they should clearly define the tools that I'm allowed to use (because there are many ways to code for a problem), and have some ability to give feedback, for example if it's a physical book it should provide some input and output tests for self-checking.

21
5

Currently I'm having an issue with WASAPI when using the format reported by the OS and it's WAVEFORMATEXTENSIBLE (which is needed for certain devices, or else the audio stream won't open with E_INVALIDARGS all for standard IEEE floating point format WITH NO CHANGES!!!), meaning I get no sound even though the stream is initialized and stuff.

However, every time I try to search any WASAPI related issues, all I get is either 10+ years old stackoverflow posts at best (I'd rather die a painful death than to re-register to that hellsite - I got a year long ban every time I posted there, once exactly due to asking about WASAPI, and all I got told to just use SDL, meanwhile SDL forums instead wanted me to use a 3rd party DLLs for live audio playback, by writing it first to a WAV file(!!!)), and otherwise my search result is instead flooded with general purpose Windows troubleshooting tips.

No, I also don't want to use AI slop. I don't know whether the sycophancy of AI or the elitism of stackoverflow users are worse.

22
6
submitted 2 months ago* (last edited 2 months ago) by gera@feddit.nu to c/learn_programming@programming.dev

I like writing the Game of Life as a helloworld program when learning graphics libraries because the naive algorithm is very easy to implement. It is however pretty slow. I want to try writing something more efficient than doing a whole pass through the board each frame, so I wonder which "fast" algorithm is more or less easy to understand and implement?

23
10
submitted 2 months ago* (last edited 2 months ago) by andioop@programming.dev to c/learn_programming@programming.dev

I feel this post had pretty good answers in the replies, and figured it's a post people learning programming might want to see.

24
6
submitted 3 months ago* (last edited 2 months ago) by ZILtoid1991@lemmy.world to c/learn_programming@programming.dev

I need it to get low level access to some PlayStation Dualsense controller features, such as adaptive triggers and setting colors.

UPDATE: The function is missing from the VTables likely due to vibe coding, but I found a workaround. Opening the device's pnpPath as a file will grant you evdev-like access to the device.

25
8

This question comes mainly from curiosity. I'm not quite sure how to phrase it best. Especially in a title. But I'm wondering if say you have one thread writing to a variable of an essentially primitive type and one thread reading them at the same time if there's any likelihood of the read happening while the variable is half written causing either weird values or undefined behavior.

Take something like a value of 8 bits from 00010101 to 11101000.

I'm imagining if say 4 bits are written while we try to read it the result could be something like

11100101

To play around i made this small sample rust. It passed without making garbage. Printing at first a bunch of lines stating "String = Hello!" and second "String = Hi!" without weirdness or issues. I kind of half-expected something like "String = #æé¼¨A" or a segfault.

use std::thread::{self, JoinHandle, sleep};

const HELLO: &str = "Hello!";
const HI: &str = "Hi!";

struct ExemptSyncStringSlice<'a>(&'a str);

unsafe impl Sync for ExemptSyncStringSlice<'_> {}

fn print_ptr(pointer: *const ExemptSyncStringSlice)
{
	for _ in 1..500
	{
		unsafe
		{
			println!("String = {}", (*pointer).0);
		}
	}
}

fn main()
{
	
	static mut DESYNC_POINTER: ExemptSyncStringSlice = ExemptSyncStringSlice(HELLO);

	let join_handle: JoinHandle<()> = thread::spawn
	(
		|| {
			print_ptr(&raw const DESYNC_POINTER);
		}
	);
	sleep(time::Duration::from_millis(1));
	unsafe { DESYNC_POINTER.0 = HI; }
	
	join_handle.join().unwrap();
}
view more: next ›

Learn Programming

2172 readers
2 users here now

Posting Etiquette

  1. Ask the main part of your question in the title. This should be concise but informative.

  2. Provide everything up front. Don't make people fish for more details in the comments. Provide background information and examples.

  3. Be present for follow up questions. Don't ask for help and run away. Stick around to answer questions and provide more details.

  4. Ask about the problem you're trying to solve. Don't focus too much on debugging your exact solution, as you may be going down the wrong path. Include as much information as you can about what you ultimately are trying to achieve. See more on this here: https://xyproblem.info/

Icon base by Delapouite under CC BY 3.0 with modifications to add a gradient

founded 2 years ago
MODERATORS