Function creating assertion failure - c++

I'm trying to create a function that will delete an item from an array of structs. When I enter a number (scanf("%d", num)), I get a pop-up saying I have an assertion failure and to abort the program. There was a warning on the indicated line below, but it didn't stop the program from compiling. When the program crashes the error appears on the same line:
void delete_stud(Student* s, int lsize)
{
int num = 0;
printf("What number student in the list would you like to delete?\nStudent number: ");
scanf("%d", num);
// This line ^^^
if (num <= lsize) {
for (int i = num; i <= lsize; i++) {
s[i - 1] = s[i];
}
lsize--;
}
else {
printf("Invalid value entered\n");
exit(0);
}
}
I call the function with:
delete_stud(class_list, lsize);
Any help would be greatly appreciated.

scanf("%d", &num);
Note the ampersand.

Related

Array prints random symbols

I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}

For loop only executes once, raising a number to another number

New to programming/coding, and couldn't get why my code doesn't work.
It's supposed to show you the result of raising a number to another number. But it only ends up looping once.
Example of error:
Input an integer: 3
Raise integer to what number: 4
3 raised to 4 is 9
My code:
#include <stdio.h>
int raiseToPow(int nNum1, int *nResult) {
*nResult = nNum1 * nNum1;
}
int main() {
int nNum1, nNum2, nResult, i;
printf("Input an integer: ");
scanf("%d", &nNum1);
printf("\n");
printf("Raise integer to what number: ");
scanf("%d", &nNum2);
printf("\n");
for (i = 0; i < nNum2; i++) {
raiseToPow(nNum1, &nResult);
}
printf("%d raised to %d is %d", nNum1, nNum2, nResult);
}
you should initialize nResult by 1 because your variable doesn't have anything inside. Also, replace *nResult = nNum1 * nNum1 by *nResult = *nResult * nNum1
It's looping the right number of times, you just need to put the print inside the loop. Also you should add a newline to the end of your print.
for(i = 0; i < nNum2; i++)
{
raiseToPow(nNum1, &nResult);
printf("%d raised to %d is %d\n", nNum1, nNum2, nResult);
}

Segmentation fault -- Alphabetically sorting a list

I was given a file with several recipes denoted at the beginning by 0. Each recipe is followed by it's ingredients denoted at the beginning by 1 as shown below :
char *rawRecipes[]={
"0Broccoli Coleslaw",
"1olive oil",
"1white vinegar",
"1white sugar",
"1package chicken flavored ramen noodles",
"1broccoli",
"1carrots",
"1green onions",
"1sunflower seeds",
"0Creamy Broccoli Salad",
"1broccoli",
"1red onion",
I'm trying to alphabetically sort the ingredients in a list, but I'm getting segmentation fault. I would greatly appreciate your help on this. Here is what I've done:
int main(void)
{
int input;
printf("\n");
printf("\n");
printf("Enter a command by number\n");
printf("4. List All Ingredients in alphabetical order\n");
printf("Give input: ");
scanf("%d", &input);
if (input == 4) // List All Ingredients in alphabetical order
{
int i = 0,k;
char alphabet[1000] ;
while(strcmp(rawRecipes[i], "") !=0)
{
if(rawRecipes[i][0] == 1 && rawRecipes[i+1][0] == 1)
{
char temp;
for(k=0; k<250; k++)
{
alphabet[k] = rawRecipes[i];
alphabet[k + 1] = rawRecipes[i + 1];
}
if(strcmp(alphabet[i], alphabet[i + 1] > 0))
{
temp = alphabet[i];
strcpy(alphabet[i], alphabet[i + 1]);
strcpy(alphabet[i + 1], temp);
}
}
i++;
}
int m;
for(m=0; m < 250; m++)
{
printf("%d: %c", m, alphabet[m]);
}
}
return 0;
}
In this code:
int i,k;
char alphabet[1000] ;
while(strcmp(rawRecipes[i], "") !=0)
What do you expect the value of i to be?
That value is undefined, and could be 0, -10000, or 10000000. Some of the possible values will cause immediate crash right on the first iteration through the loop, while trying to construct an argument to strcmp (due to i being out of range for access to rawRecipes).
You probably want: int i = 0, k;.
There are other bugs as well.
You should really learn how to use a debugger, and how to debug small programs.
And before debugging, you should turn on compiler warnings, and fix all of the bugs compiler will tell you about.
Here is one from GCC:
t.c:41:37: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
41 | alphabet[k] = rawRecipes[i];

Replace all 0's with 5's in a given number using sprintf and sscanf

I am trying to replace all the 0's present in a given integer with 5's.
To do that i am using sprintf to convert integer to string and do the operations on the string and finally convert back the string into an integer
Below is the code:
#include<stdio.h>
int main() {
int num=0, i=0;
char str[10];
printf("Enter the number: ");
scanf("%d",&num);
sprintf(str,"%d",num);
printf("string str:%s",str);
while(str[i]!='\0')
{
if(str[i]==0)
str[i]=5;
i++;
}
sscanf(str,"%d",&num);
printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);
}
I am getting wrong output
Could someone identify and correct what is wrong here. Thanks :)
scanf("%d", num); should be scanf("%d", &num);.
Also, this here
if (str[i] == 0)
str[i] = 5;
should be
if (str[i] == '0')
str[i] = '5';
Because 0 is just the same as '\0', but you want to replace the character representing 0.
Also, in your output, you got before and after mixed up.
if(str[i]==0)
str[i]=5;
must be
if(str[i]=='0')
str[i]='5';
I also encourage you to check the initial scanf returns 1 to know if the user enter or not a valid input
and in
printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);
to produce the \n at the end to have
printf("Before replacement: %s\n", str);
printf("After replacement: %d\n", num);
but note you write the string after the replacements rather than before, you have to move the case before before the while or to just remove it because you already written the string before the replacements
Example :
#include<stdio.h>
int main() {
int num=0, i=0;
char str[10];
printf("Enter the number: ");
if (scanf("%d",&num) != 1)
puts("invalid input");
else {
sprintf(str,"%d",num);
printf("string str:%s\n",str);
while(str[i]!='\0')
{
if(str[i]=='0')
str[i]='5';
i++;
}
sscanf(str,"%d",&num);
printf("After replacement: %d\n", num);
}
return 0;
}
Compilation and executions :
pi#raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi#raspberrypi:/tmp $ ./a.out
Enter the number: aze
invalid input
pi#raspberrypi:/tmp $ ./a.out
Enter the number: 10204
string str:10204
After replacement: 15254
pi#raspberrypi:/tmp $
private static void ReplaceZeroWithFive()
{
int[] arr = { 10000, 100005, 8978005, 90000007 };
foreach (var item in arr)
{
int output = GetModifiedNumber(item);
Console.WriteLine($"no :{item} , updatedwith :{output}");
}
}
private static int GetModifiedNumber(int number)
{
if (number == 0) return 5;
int result = 0, dec = 1;
while (number > 0)
{
int rem = number % 10 == 0 ? 5 : number % 10;
result += rem * dec;
number /= 10;
dec *= 10;
}
return result;
}

Implicit declaration of printf

I'm getting implicit declaration error. Please help. I don't know how to explain it in terms of words, I'd appreciate it very much if you could help me with error. It's my assignment at school and I want to resolve the issue. Please help.
#include<stdio.h>
int printmenu(int *size_of_char);
int get_char(int **size_of_char);
int main() {
int choice = 0, size_of_char;
while (choice == 0) {
printf("Enter the size of the array: ");
scanf("%d", &size_of_char);
if (size_of_char <= 0) {
printf("Invalid input\n");
}
else {choice = printmenu(&size_of_char);
}
}
return 0;
}
int printmenu(int *size_of_char) {
int x;
printf("Menu\n\n");
printf("0. Input characters\n");
printf("1. Shift Elements to Right\n");
printf("2. Combinations of 2 digits\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &x);
if (x == 0) {
get_char(&size_of_char);
}
}
int get_char(int **size_of_char) {
char string[**size_of_char];
for(int i = 0; i < **size_of_char; i++){
printf("Enter value: %c ", i+1);
scanf("%c", &string[i]);
for(int i = 0; i < **size_of_char; i++){
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
//printf("Your grade in subject %d is %f.\n", i+1, *(grades + i));
}
}
}
Thanks
You've correctly included the header which declares printf in the example that you show.
There are other bugs however:
char string[**size_of_char];
This is ill-formed. The size of an array must be a compile time constant. That expression isn't.
int printmenu(int *size_of_char)
printmenu is declared to return int, but there is no return statement. The behaviour of the program is undefined.
// int **size_of_char
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
You're trying to print a int* with a wrong format specifier. The behaviour of the program is undefined.