Inserting a number into dynamic array in C - c

I am a new to C and I need to make a function that inserts a number to a 2D dynamic array depending on what is its last number in octal representation. I tried doing something like this.
Function generating an array:
void genArr(int m, int n, unsigned int** arr) {
arr = (unsigned int**)malloc(m * sizeof(unsigned int*));
for (int i = 0; i < m; i++) {
arr[i] = (unsigned int*)malloc(n * sizeof(unsigned int));
}
}
Function to insert numbers:
void insertToArr(unsigned int** arr) {
unsigned int num;
printf("Enter a number: \n");
for (int i = 0; i < 100; i++) {
scanf("%d", &num);
if (num != 0) {
switch (num % 8) {
case 0:
break;
case 1:
arr[1][i] = num;
break;
case 2:
arr[2][i] = num;
break;
case 3:
arr[3][i] = num;
break;
case 4:
arr[4][i] = num;
break;
case 5:
arr[5][i] = num;
break;
case 6:
arr[6][i] = num;
break;
case 7:
arr[7][i] = num;
break;
}
}
else if (num == 0) {
break;
}
}
}
But I keep getting exception error:
Unhandled exception at 0x00007FF630C019DE in App4.exe: 0xC0000005: Access violation reading location 0x0000000000000010.
I'm stuck and don't really know what is wrong.

Related

Convert the array to a number starting with 0.x (C)

I have a function for translating the fractional part of the entered number into another number system (not the most beautiful code):
void FracToAny(double D, int q, int t)
{
double b[10] = {0};
for (int i = 1; i < t; i++)
{
double DP = D * q;
D = modf(DP, &b[i]);
if (D == 0)
{
break;
}
D = DP - b[i];
}
for (int i = 0; i < t; i++)
{
if (q == 16)
{
switch ((int)b[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d", (int)b[i]);
break;
}
}
}
}
As a result, I get an array of double, which is a character-by-character representation of the resulting fractional part. However, I would like to return this value from the function in the form of "0.result". How can I do this?
It would be good not to use union or dynamic memory allocation (I've seen them trying to find a solution to the problem). I'd like to make it as simple as possible.
I think this is what you are trying to do (see my comment above):
Mac_3.2.57$cat etFract.c
#include <stdio.h>
#include <math.h>
int main(void)
{
int i;
double D;
int t = 3;
double b[10] = {0};
D = (3 * 16*16*16 + 4 * 16*16 + 5 *16)/(16*16*16.0);
printf("translating %f...\n", D);
for(i = 0; i < t; i++){
b[i] = modf(D, &D);
if(D == 0){
break;
}
D = b[i] * 16;
}
printf("0.");
for(int i = 0; i < t; i++){
switch((int)b[i]*16){
case 10:
printf("A\n");
break;
case 11:
printf("B\n");
break;
case 12:
printf("C\n");
break;
case 13:
printf("D\n");
break;
case 14:
printf("E\n");
break;
case 15:
printf("F\n");
break;
default:
printf("%d", (int)(b[i]*16));
break;
}
}
printf("\n");
return(0);
}
Mac_3.2.57$cc etFract.c
Mac_3.2.57$./a.out
translating 3.269531...
0.450
Mac_3.2.57$

I don't understand this crash

This is my code for solving the problem "Students Marks Sum" in Hackerrank:
(Link: https://www.hackerrank.com/challenges/students-marks-sum/problem?)
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int marks_summation(int* marks, int number_of_students, char gender) {
int result = 0;
switch (gender){
case 'b':
while(marks != NULL){
result += (*marks);
marks += 2;
}
case 'g':
++marks;
while(marks != NULL){
result += (*marks);
marks += 2;
}
break;
}
return result;
}
int main() {
int number_of_students;
char gender;
int sum;
scanf("%d", &number_of_students);
int *marks = (int *) malloc(number_of_students * sizeof (int));
for (int student = 0; student < number_of_students; student++) {
scanf("%d", (marks + student));
}
scanf(" %c", &gender);
sum = marks_summation(marks, number_of_students, gender);
printf("%d", sum);
free(marks);
return 0;
}
When I move this code into an IDE (in my situation, it's DEV C/C++), it was crashed when my debug ran into my function marks_summation.
Error in line:
result += (*marks);
The problem is in your assumption that if you move out of the range of dynamically allocated memory the pointer value will change to NULL:
while(marks != NULL){
result += (*marks);
marks += 2;
}
There are a number of approaches you can pick to iterate over such array.
You can calculate the memory address that will no longer be valid to read and check at each iteration if your pointer is smaller than it:
int marks_summation(int* marks, int number_of_students, char gender) {
int result = 0;
int* marksEnd = marks + number_of_students;
switch (gender){
case 'b':
while(marks < marksEnd){
result += (*marks);
marks += 2;
}
case 'g':
++marks;
while(marks < marksEnd){
result += (*marks);
marks += 2;
}
break;
}
return result;
}

How can I call my array in one function to another function and display specific data from that array?

#include <stdio.h>
int main(void) {
int choice;
do {
choice = getUserChoice();
switch (choice) {
case 1:
gameResults();
break;
case 2:
printf("game results:\n ");
break;
case 3:
printf("selected choice is 3\n");
break;
case 4:
printf("selected choice is 4\n");
break;
case 5:
//this case is to keep the default from triggering when selecting 5.
break;
default:
printf("please select a valid number 1-5.\n");
system("pause");
}
} while (choice != 5);
}
int getUserChoice() {
int x = 0;
printf("[1]Enter game results.\n");
printf("[2]Current record (number of wins, losse, and ties)\n");
printf("[3]Display ALL results from all games won.\n");
printf("[4]Display ALL results ordered from low to high.\n");
printf("[5]Quit.\n");
scanf_s("%d", &x);
return x;
}//end getUserChoice
int gameResults() {
int gameInput[1][2];
//counter variables for loop.
int i, j;
for (i = 0; i < 1; i++) {
for (j = 0; j < 2; j++) {
printf("please enter a value for gameInput[%d][%d]: ", i, j);
scanf_s("%d", &gameInput[i][j]);
return gameInput[i][j];
}
}
}
void prinGameResults() {
gameResults();
int wins, ties, losses = 0;
if()
}
So essentially I'm working on this assignment that is asking me to create a 2D array, have the user select stuff from a menu, put in 2 values for 2 team scores (one being "your" team and the other one being the opponents) I've created the array and now I'm looking to display this array when the user calls the 2nd switch case, and display numbers of wins, ties, etc etc.. the only problem is I have no idea how to call this array into one function from another, perhaps I'm doing this the in a wrong way, is there some easier way of going about this array?
You'll want to define your array inside main so that it can be passed as an argument (alongside its dimensions) to each function.
#include <stdio.h>
#include <stdlib.h>
int getUserChoice(void);
void getGameResults(size_t n, size_t m, int res[n][m]);
void printGameResults(size_t n, size_t m, int res[n][m]);
#define ROWS 1
#define COLS 2
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(ROWS, COLS, results);
break;
case 2:
printGameResults(ROWS, COLS, results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(size_t n, size_t m, int res[n][m]) {
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < m; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}
And for compilers that don't support variable-length arrays, you must be more rigid in your approach. There are a few ways to do this, here is one example:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 1
#define COLS 2
int getUserChoice(void);
void getGameResults(int res[ROWS][COLS]);
void printGameResults(int res[ROWS][COLS]);
int main(void) {
int results[ROWS][COLS] = { 0 };
int choice;
while ((choice = getUserChoice()) != 5)
switch (choice) {
case 1:
getGameResults(results);
break;
case 2:
printGameResults(results);
break;
case 3:
puts("Selected (3)");
break;
case 4:
puts("Selected (4)");
break;
default:
puts("Select a valid option (1-5)");
break;
}
}
int getUserChoice(void) {
int x = 0;
puts("[1]Input results.");
puts("[2]Display results.");
puts("[3]--");
puts("[4]--");
puts("[5]Quit.");
if (scanf("%d", &x) != 1) {
fprintf(stderr, "Failed to read choice.\n");
exit(EXIT_FAILURE);
}
return x;
}
void getGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Enter a value for [%zu][%zu]: ", i, j);
if (scanf("%d", &res[i][j]) != 1) {
fprintf(stderr, "Failed to read result.\n");
exit(EXIT_FAILURE);
}
}
}
}
void printGameResults(int res[ROWS][COLS]) {
for (size_t i = 0; i < ROWS; i++) {
for (size_t j = 0; j < COLS; j++) {
printf("Value for [%zu][%zu]: %d\n", i, j, res[i][j]);
}
}
}

C switch returns default inside if/else

I have the following problem: i have two switch statements. They work perfectly when separated, but the minute I put both of them into an if/else. switch always returns the default(error). I am sorry for the difficult wording, now I have copied in the whole program so you can check it, I have tried what you said, but it didn't seem to help. So for an example, when it asks for the number, my input is 2. Then it asks for what character do I want to choose (+,-,/,*), and no matter which I write in, it gives me the default output like I have type a wrong character.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void tomb_beolvas(int *szamok);
void tomb_kiir(int *szamok);
void tomb_sorrend(int *szamok);
void sorrend_kiir(int *szamok);
void kalkulator(int *szamok);
int main() {
int szamok[10];
tomb_beolvas(szamok);
tomb_kiir(szamok);
tomb_sorrend(szamok);
sorrend_kiir(szamok);
kalkulator(szamok);
return 0;
}
void tomb_beolvas(int *szamok) {
int i;
srand(time(0));
for (i = 0; i < 10; i++) {
szamok[i] = rand() % (10) + 1;
}
return;
}
void tomb_kiir(int *szamok) {
int i;
for (i = 0; i < 10; i++) {
printf("%d\n", szamok[i]);
}
return;
}
void tomb_sorrend(int *szamok) {
int i;
int a, j;
for (i = 0; i < 10; ++i) {
for (j = i + 1; j < 10; j++) {
if (szamok[i] > szamok[j]) {
a = szamok[i];
szamok[i] = szamok[j];
szamok[j] = a;
}
}
}
return;
}
void sorrend_kiir(int *szamok) {
int i;
for (i = 0; i < 10; i++) {
printf("\n%d", szamok[i]);
}
return;
}
void kalkulator(int *szamok) {
char jel;
int a, b, donto;
printf("\nKerem valassza ki milyen modon szeretne megadni az adatokat:\n"
" 1.: egyben(peldaul 5. + 8.)\n"
" 2.: kulon(peldaul + aztan 5. es 8.)\n");
scanf("%d", &donto);
if (donto == 1) {
printf("\nKerem irja be hanyadik szamokat szeretne es koze hogy milyen kalkulaciot szeretne vegezni(pl.: 5 + 8):\n");
while (scanf("%d %c %d", &a, &jel, &b)) {
switch (jel) {
case '+':
printf("%d", szamok[a-1] + szamok[b-1]);
break;
case '-':
printf("%d", szamok[a-1] - szamok[b-1]);
break;
case '*':
printf("%d", szamok[a-1] * szamok[b-1]);
break;
case '/':
printf("%d", szamok[a-1] / szamok[b-1]);
break;
}
}
} else
if (donto == 2) {
printf("Adj meg egy jelet (+, -, *, /): ");
scanf("%c", &jel);
printf("add meg hanyadik szamokkal akarsz szamolni: ");
scanf("%d %d", &a, &b);
switch (jel) {
case '+':
printf("%d + %d = %d", szamok[a], szamok[b], szamok[a] + szamok[b]);
break;
case '-':
printf("%d - %d = %d", szamok[a], szamok[b], szamok[a] - szamok[b]);
break;
case '*':
printf("%d * %d = %d", szamok[a], szamok[b], szamok[a] * szamok[b]);
break;
case '/':
printf("%d / %d = %d", szamok[a], szamok[b], szamok[a] / szamok[b]);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
}
return;
}
There is nothing wrong with your switch statements, however:
int szamok[]={};
You can't make an empty array, you should declare it with a size:
const int size = 10;
int szamok[10];
From what I can tell, you invoked undefined behavior by accessing szamok with an out of bounds index (which is any positive number, as you got an empty array).
I'm afraid your problem is a classic scanf() issue: instead of scanf("%c", &jel); you should use
scanf(" %c", &jel); // notice the initial space before the `%c`
This skips the newline left pending after the scanf("%d", &donto);.

Why my converter doesn't count the last digit?

This program is about converting Roman number to decimal number. The program can convert the alphabet to number but it can not process the last roman digit. I think my flow is alright but the output is not right. Can any body give me a helping hand?
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[], int length) {
// Please complete the function body
int ans = 0, value[length];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
}
}
for (int i = 0; i < length - 1; i++) {
if (value[i] >= value[i+1])
ans += value[i];
else {
ans = ans + value[i+1] - value[i];
i++;
}
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
printf("roman_to_int(%s) = %d\n", roman_num,
roman_to_int(roman_num, strlen(roman_num)));
printf("roman_to_int(%s) = %d\n", roman_num_2,
roman_to_int(roman_num_2, strlen(roman_num_2)));
printf("roman_to_int(%s) = %d\n", roman_num_3,
roman_to_int(roman_num_3, strlen(roman_num_3)));
}
You should add the value of the last roman digit after the end of the second loop.
As an alternative, you could make value on entry longer than n and set the last entry to 0 so you won't need the make a special case of the last roman digit.
Note that you should also handle the case of unrecognised roman digits: either by ignoring them or by returning an error code, such as a negative value -1.
It is also simpler for roman_to_int to take a null terminated C string and compute the length there.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int roman_to_int(const char s[]) {
// Please complete the function body
int length = strlen(s);
int ans = 0, value[length + 1];
for (int i = 0; i < length; i++) {
switch (s[i]) {
case 'I': value[i] = 1; break;
case 'V': value[i] = 5; break;
case 'X': value[i] = 10; break;
case 'L': value[i] = 50; break;
case 'C': value[i] = 100; break;
case 'D': value[i] = 500; break;
case 'M': value[i] = 1000; break;
default: return -1;
}
}
value[length] = 0;
for (int i = 0; i < length; i++) {
if (value[i] >= value[i + 1])
ans += value[i];
else
ans -= value[i];
}
return ans;
}
int main() {
char roman_num[] = "III";
char roman_num_2[] = "CXXIII";
char roman_num_3[] = "MMMCDLIX";
char roman_num_4[] = "MMMCDLIZ"; // error
printf("roman_to_int(%s) = %d\n", roman_num, roman_to_int(roman_num));
printf("roman_to_int(%s) = %d\n", roman_num_2, roman_to_int(roman_num_2));
printf("roman_to_int(%s) = %d\n", roman_num_3, roman_to_int(roman_num_3));
printf("roman_to_int(%s) = %d\n", roman_num_4, roman_to_int(roman_num_4));
return 0;
}

Resources