r/C_Homework • • Aug 02 '24

int *ptr[3]; vs int (*ptr)[3];

7 Upvotes

I'm working on improving my C programming skills and have encountered a confusing aspect related to pointer declarations. I'm hoping to gain a better understanding of the differences between these two statements:

  1. int *ptr[3];

  2. int (*ptr)[3];

While they may appear similar at first glance, I believe there are significant differences in their meanings and implications. I would appreciate it if you could help me understand:

  • The fundamental differences between these two declarations

  • How to differentiate between them, considering their syntactical similarities

  • The rules or conventions in C that guide the interpretation of these statements


r/C_Homework • • Dec 05 '20

Happy Cakeday, r/C_Homework! Today you're 5

6 Upvotes

r/C_Homework • • Nov 02 '20

Can someone explain what I did wrong, because I don't understand

6 Upvotes

So basically my assignment is the following: Order the lines of the table in ascending order of the number of positive elements in each line.

#include <stdio.h>

int main()
{
	int n, m, a[50][50],swap,i,j;
	int** array;
	printf("Number of rows: ");
	scanf("%d",&n);
	printf("\nNumber of columns: ");
	scanf("%d",&m);
	if((n>50)||(m>50))
    printf("Error");
    else
    {
	for (int i=0;i<n;i++){
		for (int j=0;j<m;j++){
		printf("\tElement [%d][%d] : ",i,j);
			scanf("%d",&a[i][j]);
		}
	}

	for (int i = 0; i < n; i++)
{
    int cnt = 0;
    for (int j = 0; j < m; j++)
    {
        if (a[i][j] > 0)
            cnt++;
    }
    array[i] = cnt;
}
{
    for (int i = 0 ; i < n - 1; i++)
  {
    for (int j = 0 ; j < m - i - 1; j++)
    {
      if (array[i][j] > array[i+1][j])
      {
        swap   = array[i][j];
        array[i][j] = a[i+1][j];
        array[i+1][j] = swap;
      }

      }
    }
  }

printf("\n---------------------------------------------------------\n");
     for(int i=0;i<n;i++)
         {
         for(int j=0;j<m;j++)
         {
           printf("%d\t",a[i][j]);
           }

           printf("\n");
           }
           return 0;
        }
}

So this is what I did so far, and this is my output:

Number of rows: 3

Number of columns: 3
        Element [0][0] : -5
        Element [0][1] : -1
        Element [0][2] : 10
        Element [1][0] : 5
        Element [1][1] : 2
        Element [1][2] : 3
        Element [2][0] : -9
        Element [2][1] : 5
        Element [2][2] : 8

Process returned -1073741819 (0xC0000005)   execution time : 17.474 s
Press any key to continue.

it doesn't show the matrix and the expected result, I don't understand where the problem might be, maybe it's in the sorting algorithm that I used or what I did above. If you don't understand the assignment, basically what I'm looking for is for the program to arrange the lines on the matrix in ascending order depending on how many positive numbers it has, so fewer positive numbers or nothing means it'll go upwards (it means that it will be placed first, then it will continue placing lines or rows that have more positive numbers) and vice versa. Like this basically:

Initial matrix:

-6 8 9

-10 -9 -7

-3 -2 1

Sorted matrix:

-10 -9 -7

-3 -2 1

-6 8 9


r/C_Homework • • Dec 05 '15

Welcome to /r/C_Homework

5 Upvotes

This subreddit was just created to help divert some homework specific traffic from /r/C_Programming. If your question is not a homework assignment, feel free to post there.


r/C_Homework • • Jan 08 '26

Mobile Coding: Hustle or Waste?

4 Upvotes

I am an 18-year-old student, and I’ve always been told that C is the "Godfather" of programming and the key to Cybersecurity. Since I don't have a laptop yet, I decided not to wait and started my journey now. I’m currently using my smartphone to learn memory management and pointer logic. It’s challenging—the screen is small and the keyboard is frustrating. But honestly? It’s making me a better programmer because I have to be more precise and debug most of the logic in my head or on my notebook. To be clear: I am not looking for sympathy. I am looking for professional advice on how to manage my career path with the resources I have. I’m at a crossroads: Should I stop and work a full-time job this summer to save up for a laptop? As a girl in my local community, finding work is harder, and the wages for women are significantly lower than for men. I would have to work double the effort just to afford even a basic second-hand PC. Is this sacrifice of my time and education worth it at my age, or is it better to keep struggling and learning on a phone? Am I missing something crucial by not having a local compiler yet? I just wanted to share that the lack of tools shouldn't stop the hustle. 🌸


r/C_Homework • • Dec 05 '22

Happy Cakeday, r/C_Homework! Today you're 7

4 Upvotes

r/C_Homework • • Apr 05 '21

Effective C Chapter 2 exercise 1

4 Upvotes

Hey everyone! I've read the first two chapters of Effective C. and I love it. I think it's a really good book. Here's the question:

  1. Add a retrieve function to the counting example from Listing 2-6 to retrieve the current value of counter.

Listing 2-6

void increment(void) {

static unsigned int counter = 0;

counter++;

printf("%d ", counter);

}

int main(void) {

for (int i = 0; i < 5; i++) {

increment();

}

return 0;

}

I've "solved" the first exercise in a few different ways. For my first solution, I moved counter to a global variable. For the second, I just realized I messed up and it doesn't work. I'm wondering if moving counter to the global scope is what the author would accept as a good solution to the problem, I feel like he wouldn't. What I would like to do is write a retrieve function without passing any variables into it, and without moving counter to the global scope, but I feel like that won't work because of scope rules.


r/C_Homework • • Mar 14 '20

Simple question on homework that I am just not getting

4 Upvotes

This is the word for word question on the worksheet. It's an intro class and this question seems really simple... but void functions have been incredibly confusing for me, and I'm not confident the answer I want to give is the correct one. I'd appreciate any help!

When you call a function, as in the area and perimeter of a past assignment, you include the values to be sent to the function (the arguments) in parentheses. The function must have been defined with parameters of an equivalent type, that will be used to receive those values. If the function is called using variables, as in cout << area(length, width) for instance, what is passed to the parameters is a copy of the values in those variables. This is called call-by-value. In that case, the receiving parameters in the function are initialized to the values of the two argument variables (length and width, in our example).

Based on this, given the following function: void f (int i ) { i =57; } assuming it is called like this: f(value); where value is a variable of type int, defined as int value = 9; what would be the result of printing variable value after the call? Would value change? Explain


r/C_Homework • • Sep 27 '17

Help with basic C programming HW

4 Upvotes

I need to do a project where I make a diamond shape built with my initials, with a symbol going thru the center similar to this:

                                            c
                                           ccc
                                         cccccc
                                         $$$$$$$
                                         wwwwww
                                           www
                                            w

The number of rows for the diamond shape must be odd and between 11 and 19 randomly. the number of lines and the number of symbols in the middle must be the random number.

So far I have two triangles to make a diamond shape but I dont know how to add the symbol in the middle or incorporate srand to make the random number of rows and symbols. Our teacher didn't explain the project very well and it seems pretty complicated for a first project. Any help would be appreciated


r/C_Homework • • Jul 04 '17

Made a discord for C/C++ help! Three channels to post code and get help from advanced/experienced coders. You can chat with other coders too.

4 Upvotes

I created a discord with three help channels for those who want to get help with C/C++. Got inspiration from the Together Java discord, which has been extremely helpful for me. Join here: https://discord.gg/vnyVmAE


r/C_Homework • • Apr 08 '25

Stuck in homework, Chatgpt won't help :(

3 Upvotes

Hello everyome,

I have the following task:

Push a new element to the end of the Queue.

Requirements:

  1. Allocate memory for the new node and initialize it with the given data.

  2. Insert the node into the Queue's Linked List.

  3. Handle memory allocation failures and return ERROR or SUCCESS accordingly.

I wrote the following code:

#include <stddef.h>

#include <stdlib.h>

/* ### This struct will be used in QueueEnqueue */

typedef struct

{

list_node_type link;

int data;

} queue_node_type;

void QueueConstruct(queue_type* queue){

queue->list.head.next= &queue->list.head;

queue->list.head.prev= &queue->list.head;

}

status_type QueueEnqueue(queue_type* queue, int data) {

queue_node_type* NewNode = malloc(sizeof(queue_node_type));

if (NewNode == NULL) {

return ERROR;

}

NewNode->data = data;

NewNode->link.prev = queue->list.head.prev;

NewNode->link.next = &queue->list.head;

queue->list.head.prev->next = (list_node_type*)NewNode;

queue->list.head.prev = (list_node_type*)NewNode;

return SUCCESS;

}

but, testing fails every time.

What is the oversight here?


r/C_Homework • • Apr 09 '22

In C/C++, how can you tell if the sizeof operator will give you the size of the whole array or that of a pointer?

Thumbnail self.askprogramming
3 Upvotes

r/C_Homework • • Dec 05 '21

Happy Cakeday, r/C_Homework! Today you're 6

3 Upvotes

r/C_Homework • • Mar 16 '21

How can I make that C can apart letters from an word

3 Upvotes

First of all sorry for the hazy title and if my question isn't understood .English is my third language and is kinda hard to formulate the question clearly . Here's my problem I want to introduce a chemical substance formula like H3PO4 and the the program should separate H and to give him a variable name like x(and we will have 3x because its H3) and PO4 to be another variable like y. Or a simpler substance like HCl and the program should separate it in H and Cl .


r/C_Homework • • Oct 28 '20

why index-1 instead of index

3 Upvotes
#include<stdio.h>
#include<stdlib.h>
#define N 100

int main()
{
  unsigned int array[N];
  unsigned int index=0;

  unsigned int x=6;
  unsigned int q; //quotient
  unsigned int r; //remainder
  while(1)
   {
     q=x/2;
     r=x%2;
     array[index++]=r;
     if(0==q)
       {break;}
     else
       {x=q;}

   }
  for (int i=index-1;i>=0;i--) 
   {
     printf("%d",array[i]);


   }
  }

I dont know why int i = index-1 rather than index


r/C_Homework • • Oct 15 '20

question about arithmetic operators%%

3 Upvotes
int a=2,b=3,c=4,d=5;
	printf("a+b*d-c%%a=%d",a+b*d-c%a);
	return 0;

output is a+b*d-c%a=17

how to calculate c%%a


r/C_Homework • • Jan 07 '20

Need some help with a for loop counter

3 Upvotes

I'm trying to write a happy birthday script to stay "happy birthday (year__)" with a "for loop counter" for a class. But in the blank it will just add the given age plus 1 and print it out with out going from 1 to the given age. I'm still super new to C programming and I can't find answers anywhere else.

int age;

int counter;

printf ("what is your age?");

scanf("%d",&age)

for(counter=1; counter <=age; counter++);

printf("Happy Birthday! (year %d)" , counter);


r/C_Homework • • Oct 09 '19

Beginner in C, need help with printing

3 Upvotes

Hello!

Could someone explain why I am getting incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *'?

#include <stdio.h>

int factorial(int n);
int main()
{
	printf(factorial(3));
}

int factorial(int n){
    if (n >= 1)
        return n*factorial(n-1);
    else
        return 1;
}

r/C_Homework • • Jun 18 '19

Hi

3 Upvotes

Hello, this question is a little unusual. can someone recommend me a topic to work on my school's c programming project? my criteria for my topic is that it must solve a problem that is related to math, engineering or real-life problem. the topic cannot be too simple like showing a table of the values of sin x and cannot be too complex like making a chess engine. anyone got any suggestions? thank you


r/C_Homework • • May 24 '19

C problems with fgets and null input

Thumbnail
self.learnprogramming
3 Upvotes

r/C_Homework • • Nov 01 '18

What does "sum += str[i] - '0';" mean?

3 Upvotes

So I started problem 20 of project Euler and one solution in c was here.

The program calculates 100! and then finds the sum of the digits. It uses the gmp library, to store the large number, and is turned to a string, to get the sum of the digits. The only Thing i can't figure out is why does sum code :

sum += str[i] - '0';

need to subtract 0 or rather '0' from the string character. When I removed it I got a larger value than before.


r/C_Homework • • Oct 20 '18

Post & Pre Increment operators

3 Upvotes

Hello!

I have the following 3 examples using 'pre' and 'post' operators.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    // ex. 1
    int q = 5;
    q = ++q + q++;
    printf("\n%d", q);
    
    // ex. 2
    int e = 5;
    e = e++ + ++e;
    printf("\n%d\n", e);

    // ex. 3
    int a=10, b=5;
    int x;
    x = a++ * b-- / a++;
    printf("\n%d ", x);
}

The logic I follow when solving those:

  1. Pre-increment / pre-decrement

  2. Placing the value / substitution

  3. Post-increment / post-decrement

So the output should be:

ex. 1) q = 13

ex. 2) e = 13 ex. 3) x = 5

But in reality, the output is:

ex. 1) q = 13
ex. 2) e = 12
ex. 3) x = 4

Why ex.1 and ex.2 are different? Does it have anything to do with the associativity of the operators?

In the ex.3, the result of 'x' should not be affected by the post-increment operators, but somehow it does.

Would be very grateful if someone could explain. Thanks!


r/C_Homework • • Sep 14 '18

Problem with fgets, causing seg fault

3 Upvotes

My assignment involves reading a given .txt file and using the given data to assign values to a linked list of struct _student. My thought process was to use fgets to read each line of the txt file and assign the data accordingly. Unfortunately, I think my thought process is flawed, as I've been getting a seg fault for quite a few days now. Could anyone give any insight as to what I'm doing wrong? I'm assuming im not checking for something crucial that's breaking my code.

The input.txt file is as follows:

Calvin:21:M:1000403
Hobbes:18:M:53000
Sarah:18:F:60210
Jane:20:F:1004300

We also use scanf so the user can input the file name themself.

#include <stdio.h>
#include <stdlib.h>

struct _student{
	char name[25];
	unsigned int age;
	char gender;
	unsigned long id;
	struct _student *next;
};
typedef struct _student Student;

void add_to_end_of_list(Student *head, Student     *new_student){
	if(!head){
		head = new_student;	
		return;
	}	
	while(head->next){
		head = head->next;
	}
	head->next = new_student;
	return;
}

void print_data(Student *head){
	while(head->next){
		printf("Node at: 0x%x\nName: %s\nAge: %d\nGender: %c\nID: %lu\n Next Node at: 0x%x",	 &head, head->name[0], head->age, head->gender, head->id, &(head->next));
		head = head->next;
	}
   return;
}

int main(){
	char fname[128];
	printf("file name: ");
	scanf("%s", fname);
	FILE *file = fopen("input.txt", "r");
	printf("\n");
	char line[256];
	Student *head = NULL;

	while(fgets(line, 255, file)){
		Student *new_student = (Student *) malloc(sizeof(Student));
		sscanf(line, "%[^:]:%d:%c:%lu", (new_student->name), &(new_student->age), &(new_student->gender), &(new_student->id));
		add_to_end_of_list(head, new_student);
	}
	print_data(head);
	printf("\n");
	fclose(file);


	return 0;

}

Running this gives Segmentation Fault (Core Dumped) after inputting "input.txt". Including the line

 if(!head){return;} 

as the first line in print_data gets rid of the seg fault, but simply doesnt print any of the data in the structs. Anyone have any ideas?


r/C_Homework • • Aug 04 '18

realloc() woes

3 Upvotes

So this assignment is already submitted, and I've probably gotten an abysmal mark for code that doesn't work (pretty much solely because I didn't start early enough; I got overconfident after the previous assignments in this class). Still, I want to understand WHY it refused to work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

	char* s = (char*) malloc(sizeof(char) * 20);
	if (s == NULL) {
		printf("malloc fail");
		exit(1);
	}
	s = "string 1";
	s = (char*) realloc(s, (sizeof(char) * 21));
	s = "string 22";
	exit(0);
}

The above is a simplified version of the part of my code that never worked. It crashes when it hits the realloc() line, saying that malloc.c or raise.c can't be found, or that realloc() is not defined, depending on the specific way I mess around with the details. No compiler warnings though. I compiled the above with

gcc -ggdb -std=c99 -Wall test.c -o test

(If it matters)

Can I please get some insight into what I did wrong here? For the record, removing the cast cycles between the three errors mentioned above, depending on how I handle it precisely.


r/C_Homework • • Apr 09 '18

Occurrences of a letter in a string.

3 Upvotes

Link: https://pastebin.com/yuUA82Sh Task: 15 letters max for a string, have to find the number of duplicate occurrences of letters. If there are no duplicates print a message. I'm not sure how to print no duplicates once, I know the issue is because I have it in the for loop. I think I should be using a while loop? Not sure how to keep looping to find the occurrences but if there are none, just print once, cause it prints for every non occurrence of a letter.