Get the return value from a function - c

I want to modify a char by using a function and print it on the screen but my code cannot achieve this function. Here is my source code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long M = 2147483647;
void IntroduceError(char k[],double p)
{
int i;
for ( i = 0; i < 8; i++) {
if ((double)random()/M <= p)
k[i] = 1;
}
}
int main(int argc, char *argv[])
{
char test[] = "11110000";
double rate = atof(argv[1]);
IntroduceError(test, rate);
printf("\nErrored codeword is : %s\n",test);
return 0;
}

k is a string i.e. array of characters, but you're assigning an integer value to it.
Instead of:
k[i] = 1;
You probably want:
k[i] = '1';
Also, you should call srandom at the start of your program to seed the random number generator, passing in at least the PID, i.e. srandom(getpid()); so that you don't get the same results every time.

get in the printf statement is not defined. If you change get with test it should compile.

Related

C Program To Calculate Numbers Squared | Arguments Segmentation Fault

I'm a beginner to C, trying to write a program to calculate a square number. At my college we're not allowed to use printf() or scanf() which makes things a bit complicated.
This led me to using arguments to get input. I'm getting a segmentation fault (core dumped) when I try to compile. I think this comes from using argv and indexes but I'm not sure how to fix it.
Do you have some insight that might help? It would be much appreciated!
#include <unistd.h>
int main(int argc, char *argv[]) {
int number;
int square;
while(argc != 0) {
number = argv[1][square];
square = number * number;
write(1, &square, 1);
square++;
}
write(1, "\n", 1);
return 0;
}
The segmentation fault, if not caused by something else first will be caused here:
number = argv[1][square];//seg fault possible when square becomes
//larger than strlen(argv[1]) + 1
Attempting to access memory that the program process does not own, as above, will invoke undefined behavior.
Also, at the time this expression is executed:
square = number * number;
it is unknown what value was contained in square.
These two values should be initialized:
int number = 0;
int square = 0;//this specifically will cause problems later if not initialized
Also, at the time this is called:
number = argv[1][square];
argv[1] is a string, and needs to be converted to an integer before using.
number = atoi(argv[1]);
Next, the statement:
number = argv[1][square]; //seg fault possible as noted above.
will blow up when the value of square becomes larger than then string length of argv[1].
If your intent is squaring the value contained in argv[1] in its entirety as a single numeric value, it must first be converted from a string array, to an integer value, then you can easily get the square as you do in your code:
int number = atoi(argv[1]);
square = number * number;
If, as it appears in your code, you are interested in squaring each of the component integers making up the string, then given the input of "1234, to convert each of the digits inargv1from ASCII value to its numeric value. (i.e.val = argv1[x] - '0'==>x`), then square it, then move the the next character in the array and so on.... look at the other part of this answer below.
The following is an adaptation of your original to do this...
int main(int argc, char *argv[]) {
int number = 0;
int square = 0;
if(argc != 2)
{
printf("%s\n","Usage prog.exe <nnn>, where nnn is an integer value.\nProgram will exit.");
}
else
{
char *ptr = argv[1];
while(*ptr != '\0')
{
number = *ptr - '0';
square = number * number;
printf("%d\n", square);//write() not available on my system, replace as necessary
square++;
ptr++;
}
}
return 0;
}
So, for example given prog.exe "1234", the output is:
The completed code should look like this :
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
int number;
int square;
if(argc == 2) {
number = atoi(argv[1]);
square = number * number;
char sq_buffer[12];
sprintf(sq_buffer , "%d" , square);
strcat(sq_buffer , "\n");
write(1, (const void *) sq_buffer, strlen(sq_buffer));
}else{
char message[100];
strcpy(message , "Please specify exactly one argument \n");
write(1 , (const void *)message , strlen(message));
}
return 0;
}
When you say that you are not allowed to use 'printf', does that also include 'fprintf' and 'sprintf'? If so, then I would solve this problem like this:
void main( int argc, char **argv )
{
int i;
int j;
int square;
int value;
char buffer[256];
for (i = 1; i < argc; i++) {
/* Get the next integer from the args to the program */
value = atoi(argv[i]);
/* Calculate the square of that value */
square = value * value;
/* Now convert it to ASCII */
itoa(square, buffer, 10);
/* Write out the data */
write(1, buffer, strlen(buffer));
/* You could also use putchar() for it, like this: */
j = 0;
while (buffer[j] != '\0')
putchar(buffer[j++]);
}
}
If he doesn't want you using itoa(), then you could write your own int to ASCII conversion routine like this:
char *IntToASCII( int x )
{
static char buffer[256];
char *ptr;
int neg;
char *digits = "0123456789";
unsigned long tempX;
neg = (x < 0);
tempX = x;
if (neg) {
tempX *= -1;
}
ptr = buffer + sizeof(buffer) - 1;
*ptr = '\0';
do {
ptr--;
*ptr = digits[tempX % 10];
tempX /= 10;
} while (tempX > 0);
if (neg)
*ptr = '-';
return (ptr);
}
Or you can make 'buffer' an input parameter and remove the static declaration for it.
#define STDOUT_FILENO 1
#define MAX_INT_DIGITS (10+1) /*+1 for string null terminating*/
int main(int argc, char *argv[])
{
int number=0, square=0;
char ret_num[MAX_INT_DIGITS];
for (int i =1; i < argc; ++i)
{
number = atoi(argv[i])
square = number * number;
itoa(square, ret_num, 10);
write(STDOUT_FILENO, ret_num, strlen(ret_num));
/*write new line*/
write(STDOUT_FILENO, '\n', 1);
}
return 0;
}

Error with ToString()

I'm new to c. Please help me
Why do I get this error using eclipse
Multiple markers at this line
- request for member 'ToString' in something not a structure or union
- Method 'ToString' could not be resolved
Here is my code
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
char g = s.ToString();
char l = n.ToString();
printf(g+l);
return 0;
}
s and n are just ints; they don't have a ToString() method. Also, as #remyabel pointed out, char is not the appropriate type for storing a string value, anyway; it stores only one character.
You don't need to convert your ints to strings at all to do what you're trying to accomplish, so you actually want something like this:
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
printf("%d%d", s, n); // you can't add l to g here!
return 0;
}
// output 54
DEMO
Oh, and please use more descriptive variable names!
EDIT: To save the string, as requested in the comments, you could do this:
char myString[10];
sprintf(myString, "%d%d", s, n); // myString is now "54"
I'd suggest picking up a C tutorial and starting from the beginning. The use of ToString isn't the only thing that's wrong. You could rewrite it this way and it should work (assuming you want to print "54"):
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
char g = '0' + s;
char l = '0' + n;
printf("%c%c", g, l);
return 0;
}
But this only works as long as s and n are less than 10, and besides is overly complicated since printf is made for formatting and printing values of different types. This would work just as well:
#include <stdio.h>
int main()
{
int s = 5;
int n = 4;
printf("%d%d", s, n);
return 0;
}
If you want to use the string for something else than printing, the answer depends on what you want to do.

Beginner Here Rand in c

im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.

Islower function glitch

I'm doing the CS50x class and I am stuck at a glitch. I asked them what was going on and no one knew what was going on.
Whenever I try to print a lowercase f it always comes up as ?. Try doing 23 as the argument and abcdefghijklmnopqrstuvwxyz as the input. It's messed up. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[]){
if(argc !=2){
return 1;
}
string x = GetString();
int key = atoi(argv[1]);
for(int a = 0, n = strlen(x); a < n; a++){
char i = key + x[a];
if(islower(x[a])){
if(i > 122){
i = (i-122) + 96;
}
}
if(isupper(x[a])){
if(i > 90){
i = (i-90) + 64;
}
}
printf("%c", i);
}
printf("\n");
return 0;
}
I suspect it's because your char i defaults to signed. When you add 23 to a lowercase letter, anything that is above 104 (being 127-23) is going to wrap around into negatives. Looking at your code, it will stay negative because it fails the subsequent tests and does not get modified.
It's usually best to do char arithmetic with int, then convert back to char... But you could probably fix this by using unsigned char.

Trying to put some digits into a char array

I'm trying to create a char array made of some letters and numbers (the function was way more complex initially but i kept simplifying it to figure out why it doesn't work properly). So i have a char array in which i put 2 chars, and try to add some numbers to it.
For a reason i can't figure out, the numbers do not get added to the array. It might be really stupid but I'm new to C so here's the simplified code. Any help is much appreciated, thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char some_string[20];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = 0;
int rand_copy = 0;
random = (rand());
rand_copy = random;
int count = 2;
while ( rand_copy > 0 ) {
rand_copy = rand_copy / 10;
++count;
}
int i=2;
for (i=2; i<count; i++) {
some_string[i] = random%10;
random = random/10;
}
return (some_string);
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}
You have many problems:
resulting string is not zero-terminated. Add some_string[i] = '\0'; to fix this
character (char) is something like "a letter", but random % 10 produces a number (int) which when converted to character results in control code (ASCII characters 0-9 are control codes). You'd better use some_string[i] = (random % 10) + '0';
you're using fixed length string (20 characters), which may be enough, but it could lead to many problems. If you are a beginner and haven't learn dynamic memory allocation, than that's ok for now. But remember that fixed-length buffers are one of top-10 reasons for buggy C-code. And if you have to use fixed-length buffers (there are legitimate reason for doing this), ALLWAYS check if you are not overrunning the buffer. Use predefined constants for buffer length.
unless the whole point of your excercise is to try converting numbers to strings, use libc function like snprintf for printing anything into a string.
don't use global variable (some_string) and if you do (it's ok for a small example), there is no point in returning this value.
Slightly better version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_LENGTH 20
char some_string[BUF_LENGTH];
char *make_str() {
some_string[0] = 'a';
some_string[1] = 'x';
int random = rand();
int rand_copy = random;
int count = 2;
while (rand_copy > 0) {
rand_copy = rand_copy / 10;
++count;
}
int i;
for (i = 2; i < count; i++) {
/* check for buffer overflow. -1 is for terminating zero */
if (i >= BUF_LENGTH - 1) {
printf("error\n");
exit(EXIT_FAILURE);
}
some_string[i] = (random % 10) + '0';
random = random / 10;
}
/* zero-terminate the string */
some_string[i] = '\0';
return some_string;
}
int main(int argc, const char *argv[]) {
printf("the string is: %s\n",make_str());
return 0;
}

Resources