working with char arrays in C - c

I'm writing a method that turns a decimal number into any radix (2-36) and prints the appropriate chars to the screen. The decimalToSymbol() method works correctly. The problem I'm having is in the while loop I assign ans[i] to a char and when I try to print it immediately after it is 0. I have looked online and found this is an OK way to assign the char but am not sure what is going wrong.
void writeRadixB(int decimalNumber, int radixB)
{
char ans[80] = "";
int i = 0;
while(decimalNumber!= 0){
printf("decNum: %d div by rB: %d equals %d\n", decimalNumber, radixB, decimalN
printf("decNum: %d mod by rB: %d equals %d or char %c\n", decimalNumber, radix
printf("i: %d\n", i);
decimalNumber = decimalNumber/radixB;
ans[i] = decimalToSymbol(decimalNumber%radixB);
printf("ans[%d] is %c\n", i, ans[i]);
i++;
}
printf("(%s) radix %d", ans, radixB);
}

You shouldn't change decimalNumber until AFTER you've extracted your digit. That, and your result is backwards.

You should put the line ans[i] = decimalToSymbol(decimalNumber%radixB); before the line decimalNumber = decimalNumber/radixB;, (to not lose a digit). also, you probably want to reverse the string before printing it.

Related

C program does not recognize my input for 'max'

Hi I keep trying to figuure this out but my input keeps getting ignored, thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main(){
float a, b, a0, b0,i;
char ans;
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf(" %c", &ans);
while(ans == 'max'){
printf("maximum selected");
}
printf("minimum selected");
return 0;
}
First of all, you're comparing a single char to a whole string, so you need to modify your ans variable declaration to make it a string, like:
char ans[4]
Keep in mind, this will have a maximum size of 3. If you need to store a bigger string, you'll need to modify this.
Then, after doing this, using a while to do that comparison isn't correct. It's better to implement an if-else. And, inside that, the comparison you're doing is wrong. You need to compare strings, not chars, so you need to use strcmp() function, like:
strcmp(ans,"max") == 0
If this function returns a 0, it means both strings are equal.
Another thing to comment is that you will need to modify your scanf to scan a string, not a char, the new one will be scanf("%3s", &ans);.
And let me tell you one more thing. The for you're using has no sense. You're using a for with parameters i = 1; i <= 1; i++. That means i will start the buckle fulfilling the conditions to break it, so it will only be executed once. In other words, the code inside that for will be executed just once, no matter if it's inside or outside the for.
Anyway, and to sum up, here's your new code:
int main(){
float a, b, a0, b0,i;
char ans[4];
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf("%3s", &ans);
if(strcmp(ans,"max") == 0)
printf("maximum selected");
else
printf("minimum selected");
return 0;
}

Got some segmentation error when use struct pointer in for loop in C

Here is some simple code that prints struct values
in_hotel_info function is used to get struct inputs.(And yes, I use 'gets' because my professor forced me to use it sadly). And also When I put "0" as an input, it ends and returns its input numbers.
And I used sscanf to scan strings and numbers.
#include <stdio.h>
typedef struct hotel_info hotel;
struct hotel_info
{
char name[30];
int rank;
double popular;
double far;
char breakfast;
};
int in_hotel_info(struct hotel_info *p);
void out_hotel_info(struct hotel_info *p, int N, int G, double D);
int main(void)
{
hotel hotels[100];
hotel *p;
int number = 0, ranks, fars, i;
number = in_hotel_info(hotels);
p = hotels;
printf("%d\n", number);
getchar();
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
}
int in_hotel_info(struct hotel_info infos[])
{
char inputs[100];
hotel* p;
p = infos;
int cnt = 0;
while (1)
{
gets(inputs);
if (strcmp(inputs, "0") == 0)
{
break;
}
else
{
sscanf(inputs, "%s %d %lf %lf %c", p->name, &p->rank, &p->popular, &p->far, &p->breakfast);
}
p++;
cnt++;
}
return cnt;
}
The problem is, when I tried to print
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
what I expected is
mike 2 3.5 4.24 Y
but I constantly got a segmentation error.
The problem is, when I tried to print
for (; p < p+number; p++)
{
printf("%s %d %lf %lf %c\n", p->name, p->rank, p->popular, p->far, p->breakfast);
}
the problem is p < p+number is always true when number is strictly positive, so the for never ends and you access out of the array with an undefined behavior (your segmentation fault).
you have additional problems
gets is very dangerous to use because it can write out of the array, use fgets or scanf (secifying max length to read), in the considered case you can read a number then check if it is 0 or not
in in_hotel_info in case the user enter more than than entrie you write out of the array, you need to get the max number of element to read in argument
when you read p->name in case the enter name longer than 29 you write out of the array, limit the size using %29s rather than %s. ALso to bypass spaces at the beginning of the name use %29s (with a space before)
you do not check scanf returns 5, so you do not detect invalid inputs
The getchar(); in main is strange

What does "%d! = %ld'n" mean in this code?

I'm still a beginner at C, so I'm finding difficulty in understanding "%d! = %ld".
I know that %d and %ld are respectively used for an integer and long, so "! =" is confusing me.
#include<stdio.h>
long factorial(int);
int main() {
int n;
long f;
printf("Enter an non-negative integer: ");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else {
f = factorial(n);
printf("%d! = %ld\n", n, f); //what does this mean?
}
return 0; }
long factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1)); }
This will print:
%d, i.e. the decimal value of int n
! =, i.e. the literal character sequence
%ld, i.e. the decimal value of long f
%d and %ld are the formatting placeholders for int and long int in printf. The exclamation point is just the factorial symbol, as mentioned in the comment.
printf() allows you to print a string with variables inside of it. Let's say you have a variable i, containing an integer, 7.
printf("My variable is %d", i);
Will print
My variable is 7
to the console! That's because %d is how you tell printf(), "Hey, put an integer variable here!". The integer is then supplied as the next argument to the function. In your case, %d represents the integer n, and %ld represents the long integer f. Since f might be really big, we make it a long, which means more bytes are allocated to it internally on your computer. So for example, if we wanted to get the factorial of 5 and print it, we might do the following:
printf("Factorial of %d equals %ld\n", 5, factorial(5))
// this will print "Factorial of 5 is 120" then a newline
Oh, and \n just means print a newline afterwords!
printf("%d! = %ld\n", n, f); //what does this mean?
%d - print an integer as a signed decimal number.
l - specifies that the argument is a long int or unsigned long int as appropriate. %ld then prints a long int or unsigned long int
The printed text will become something like
n! = f
(factorial notation n!)

Finding largest and smallest numbers using atoi

scanf("%1c%2c %d %d %d %d %d %d %d %d %d %d",
&x, &y, &arr[0], &arr[1], &arr[2], &arr[3], &arr[4],
&arr[5], &arr[6], &arr[7], &arr[8], &arr[9]);
strcpy(string, x);
value1 = atoi(string);
strcpy(string, y);
value2 = atoi(string);
value_final = value1 + value2;
I'm trying to get the ascii values for the -l or -s then pass them through the switch with the ascii values added but I'm getting errors when I use atoi and I'm not sure as to if you are supposed to be adding the ascii values when the user enters the -l or -s or if their is another way to do this?
Your code has several problems:
Major: the switch cases do not have a break; clause. Control falls into the next clause and finally into the default statement.
Major: your show confusion between char arrays and single char variables: strcpy(string, x); should not even compile.
Your method for parsing -l or -s is very convoluted and probably erroneous. You should use character literals.
You do not need a double loop to find the smallest or the largest element in an array. A single loop suffices, and the printf statement should be outside the loop. max and min are uninitialized, the loops invoke undefined behavior.
the title says using atoi(): if this was your assignment, you should not use scanf().
Here is a simplified version:
int main(void) {
char option[3], buffer[32];
int i, min, max, value;
min = max = 0;
if (scanf("%2s", option) == 1) {
for (int i = 0; i < 10 && scanf("%31s", buffer) == 1; i++) {
value = atoi(buffer);
if (i == 0) {
min = max = value;
} else {
if (min > value)
min = value;
if (max < value)
max = value;
}
}
if (!strcmp(option, "-l")) {
printf("output: The largest number is %d\n", max);
return 0;
} else
if (!strcmp(option, "-s")) {
printf("output: The smallest number is %d\n", min);
return 0;
}
}
printf("You have entered an invalid option, try again next time.\n");
return 0;
}

concatenating char to int type

Been racking my brain for the past few hours but i need help. Pretty much trying to write a C model for a blocking cache to be used in a RTL design. I've defined the cache line in C as an array of 'char' types to make it byte-addressable. Only difficulty is I can't for the life of me figure how to concatenate four bytes (chars) into a 32bit 'int' type to be returned. I've tried everything I could think of using strcat, strncat, strcpy, etc but no luck. strcat returns the proper value when I the char array is populated with actual characters, but it doesn't behave as desired when numbers are use (strcat only returns the first element instead of the entire char array). Example code:
unsigned char aa[4] = {0};
char testet[2] = {1,0};
printf(" aa[0] = %d \n", aa[0]);
printf(" aa[1] = %d \n", aa[1]);
printf(" aa[2] = %d \n", aa[2]);
printf(" aa[3] = %d \n", aa[3]);
printf(" aaconcat as a 32b word is %u \n", *strncat(aa, testet,2));
printf(" aaconcat as a 32b word is %u \n", *strncat(aa, testet,1));
printf(" aa[0] = %d \n", aa[0]);
printf(" aa[1] = %d \n", aa[1]);
printf(" aa[2] = %d \n", aa[2]);
printf(" aa[3] = %d \n", aa[3]);
Returns:
aaconcat as a 32b word is 1
aaconcat as a 32b word is 1
aa[0] = 1
aa[1] = 2
aa[2] = 1
aa[3] = 0
Though I'm expecting {testet[0],testet[1],testet[0]} = 131330.
if you are trying to concatenate the actual bits, which I suspect you may be trying to do given your expected result from {testet[0],testet[1],testet[0]} = 131330, then try something like this to concatenate the chars:
This assumes the chars you want to concatenate are stored in unsigned char chararr[4].
long int chars_in_int = 0;
for (int i = 0; i < 4; i++ ) {
chars_in_int << 8; /* redundant on first loop */
chars_in_int += chararr[i];
}
This will place the chars with the lowest index in chararr in the most significant bits of chars_in_int.

Resources