I'm new to the world of C programming, and I as trying to code a primitive, terminal-based version of the "Hangman" game.
One of the steps doing this (or at least the way I am working on), is to create a second char array (next to the original char array that stores the word one needs to guess), filled with "*" for every Char of the original array, and display it. Although the rest of the programming part is not there yet (since I am not finished with it yet), I doubt it is relevant for now (however I allready know how to proceed, that is if I weren't bothered by some error-messages)....
Here's the code I have so far:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
void hiddenArray(char array[]);
char *secretWord;
char *arrayCover;
char letter;
int main(int argc, char *argv[]){
secretWord = "Test";
printf("Welcome to the Hangman!\n\n");
hiddenArray(secretWord);
printf("What is the hidden Word?: %c\n", *arrayCover);
printf("Guess a letter\n");
scanf("%c", &letter);
}
void hiddenArray(char array[]){
int size,i;
size = sizeof(*array);
for (i=0;i<size-1;i++){
*(arrayCover+i) = "*";
}
}
Now I have two issues... the first one:
I don't understand the error message I am getting after compilation:
pendu.c:41:19: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
*(arrayCover+i) = "*";
^ ~~~
1 warning generated.
And my second question: the second Array created, filled with "*" is not being displayed, what did I do wrong?
I'd love for some help, cheers!
Your program have some errors to be corrected .
1) Your *arraycover is pointing to some unknown value, You have not initialized it.
2) sizeof(*array) should be sizeof(array)
3) *(arrayCover+i) = "*" should be *(arrayCover+i) = '*';
I suggest you not to create too many global variables when you dont really need them
Create char secretWord[100] = "Test" instead of char *secretWord
Try this
size = sizeof(arrayCover)/sizeof(char);
for (i=0;i<size-1;i++){
*(array+i) = '*';
}
Despite of all these, I think you need to allocate memory for arrayCover
arrayCover = malloc(sizeof(char) * number_of_elements);
"*" is a string. Use '*' instead to get the char.
"*" is a string which also contains \0 also, resulting to 2 characters. Instead use '*' which is just a character.
The function hiddenArray has the formal argument array which need to be used locally instead of arrayCover as below,
void hiddenArray(char array[]){
int size,i;
size = sizeof(array)/sizeof(array[0]);
for (i=0;i<size-1;i++){
*(array+i) = '*'; /* Or array[i] = '*' */
}
}
Related
I've been working on readability and I really am stuck as to what I've done wrong/what I'm missing.
#include <stdio.h>
#include <math.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main() {
string text = get_string("Text: ");
int sentences = 0;
int numberOfCharacters = strlen(text);
string characters[numberOfCharacters];
int words = 0;
for (int i = 0; i == numberOfCharacters; i++) {
if (isspace(characters[i]) == 0) {
words ++;
}
}
for (int i=0; i < numberOfCharacters; i++) {
if (text[i]=='.') {
numberOfCharacters++;
}
}
int averageWords = characters / words * 100;
int index = 0.0588 * round(characters) - 0.296 * round(sentences) - 15.8;
printf("Grade %d \n", index);
}
The error I get from that, using help50, is: readability.c:26:35: error: invalid operands to binary expression ('string [numberOfCharacters]' and 'int')
Which I don't understand, so please if possible help :)
In cs50 string is a typedef of char*, so what you have there is:
char *characters[numberOfCharacters];
Which is an array of pointers, they are not initialized in any way, in your next statements you accessing these unitialized values and you are passing an incompatible argument to isspace.
Furthermore, the expression:
int averageWords = characters / words * 100;
Is odd, you're dividing an array of pointers to char (wich decays to a pointer, but that's beside the point), by an int. That's where the error stems from, but you need to correct the rest.
Not to mention round(characters) which is also very strange, that function expects a double argument, but again, you are passing to it an array of pointers.
The name string is defined as an alias for the type char *. So this declaration
string characters[numberOfCharacters];
is equivalent to the declaration
char * characters[numberOfCharacters];
So in this expression
isspace(characters[i]) == 0
the argument characters[i] has the type char * while the function expects an argument of the type int.
So you need at least to declare
char characters[numberOfCharacters];
But in any case this loop
for (int i = 0; i == numberOfCharacters; i++) {
if (isspace(characters[i]) == 0) {
words ++;
}
}
does not make a sense because the array characters was not initialized.
It seems within this loop you were going to use text instead of characters.
This expression
int averageWords = characters / words * 100;
is entirely wrong and does not make a sense. You are trying to divide a pointer ( after implicit conversion the array characters to a pointer to its first element) by an integer. But such an operation is not defined for pointers.
So it is unclear what the program does.
First Issue:
string is defined as char * so this is wrong:
string characters[numberOfCharacters];
That is giving you an array of strings, not a string of length numberOfCharacters
Change that to this:
char characters[numberOfCharacters];
Second Issue:
characters is uninitialized when first used, you could of meant to use text instead in the loop
Third Issue:
Performing math (round(characters) and characters / words * 100) on a string or array is certainly wrong and makes no sense, so I am not sure what you are attempting to do here
I reviewed the clear issues, but since it is unclear what your program is trying to do, I cannot provide further feedback
My code:
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
In the above code the output:
value of area: 50
Process returned 0 (0x0) execution time : 2.909 s
Press any key to continue.
There is a new line inserted, but when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler and no newline printed out. Why???
Also, I modified my code as,
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%c", k);
return 0;
}
The output is only the area calculated and the new line but k is not printed out. I also find this very weird! Can you please give suggestions?
Please be kind enough with the suggestions and point out my mistakes because I am a beginner at C.
The problem is that you are trying to save a string as a char, so you have to change const char k = "hjk" to const char k[]="hjk" and print it using %s instead of %c.
#include<stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k[]="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%s", k);
return 0;
}
Some clarification: if you save a "string" without specifying that it is an array of characters char[], if you try to print it as a char %c a warning would be generater (warning: incompatible pointer to integer conversion initializing 'const char' with an expression of type 'char [4]') and if you try to print it as a array of characters %s (string) you are going to receive a segmentation fault.
when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler
const char NEWLINE = "\n"; is invalid C. The reason why it is invalid is explained in detail here: "Pointer from integer/integer from pointer without a cast" issues
The compiler is not required to produce an "error", but it is required to produce some sort of diagnostic message. See What must a C compiler do when it finds an error?
Why your compiler decided to spew out a binary regardless of getting fed invalid C is anyone's guess. You have to ask the people who made the compiler. In case of gcc, you won't find an answer, because this is completely undocumented behavior.
And therefore, any output you get from such a "non C" program is also completely non-deterministic, unless a compiler documented the behavior among non-standard compiler extensions. gcc did not.
Similarly, const char k="hjk"; is also invalid C.
k seems an array of char.
Try to use:
const char k[] = "something";
printf("%s", k);
The statement const char k="hjk"; is not valid C code. Apparently, your compiler accepts it and assigns the memory address where the literal string "hjk" begins to k. Both a memory address and a char are implemented as integer numbers, so the memory address is interpreted as the numeric code for a character.
Because k is now, most likely, an unprintable character, printf("%c", k); will print nothing.
Exactly the same happens when you do const char NEWLINE ='\n';.
I've looked around everywhere and tried pretty much everything suggested and can't get anything to work.
this is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
float a;
char *nums[3];
char str[5];
printf("Please enter a,b,c:");
scanf("%s",str);
int i=0;
char *p;
p = strtok (str,",");
while (p != NULL)
{
nums[i++] = p;
p = strtok (NULL, ",");
}
a=atof(nums[0]);
printf("%s\n",nums[0]);
printf("%f\n",a);
return 0;
}
the math.h is for something later on after I figure this out. So if I entered "1,2,3" into this program, my print statements would show me "1" and then "0.000", this is obviously just there for me to test things out but why the does my value just disappear after trying to convert to a float? I need that value of 1 to do math with later in my program but I can't get that char pointer value no matter what I try, I can only seem to print it, but it screws up as soon as I try to convert it into a type I can use.
Two issues:
You nums and str arrays are too short. nums should have a size of at least 3, and str should be at least 6 ("1,2,3" plus null byte), probably more for larger numbers.
So change those to:
char *nums[3];
char str[20];
Second, you don't #include <stdlib.h>, which contains the declaration of atof. Without a declaration, it is assumed to return an int.
Fix the array sizes, and #include <stdlib.h>, and it should work.
I'm working on my assignment for my C course, and I'm trying to take in the user's input and store it in a variable to use for later in my code. Here's what my main function looks like,
int main() {
// Variables here
char* inputLine[10];
do {
printf("Insert number....");
scanf("%s\n", inputLine);
// More stuff here
}
return 0;
}
This code gives me a bunch of warnings, warning: format specifies type 'char *' but the argument has type 'char **' [-Wformat], and if I change the variable declaration to,
char* inputLine = NULL;
When I execute my code I get a seg fault, can someone explain to me what I am doing wrong, and the differences of what happens in the memory when I'm initializing this variable?
char* inputLine[10];
--> is an array of ten pointers to char
printf's format %s expects argument of type char *, but you're providing it as type char **
Just use
char inputLine[10];
To avoid possible buffer overflow you should use
scanf("%9s", inputLine); //Notice the size with %s
9 only because C string are null terminated ('\0') so one extra byte for it goes at end
char inputLine[10];
do {
printf("Insert number....");
scanf("%9s\n", inputLine);
// More stuff here
} while( //some condition);
However if you edit your code and remove * you get answer, but normal array deprecated, nowdays, programmers use vector, normal array in C not safe :
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> inputLine;
You can define with every data type:
vector<int> myvar;
Or you can define multidimensional vector:
vector< vector <int> > myvar;
I just returned to develop in C over eclipse and im having big issues im not sure how to solve, dont remember i used to have such when developing before. anyway i'll point u to 2 issues (i made my example easy-to-post in here):
#include <stdio.h>
int change_array(char *str, char *a[]) {
a[0] = "changed [0]";
if (fgets(str, 200, stdin) != NULL) {
}
return 0;
}
int main() {
char str[200];
char a[15][200];
change_array(str, a);
printf("a[0]: %s\n", a[0]);
printf("str: %s\n", str);
return 0;
}
getting a warning in line "change_array(str, a)": passing argument 2 of ‘change_array’ from incompatible pointer type [enabled by default] - why??
after running my 'doing-nothing' code sample output is:
some-value
a[0]: � <------- wired characters appear
str: some-value
The issue is here... int change_array(char *str, char *a[])
The dimension of a is undefined, so it doesn't know how far to step each *a and a is an array of pointers to char. However, you are passing in an array of arrays of 200 char. Thus the incompatible types error.
I believe your issue goes away with...
int change_array(char *str, char (*a)[200])
in which case a is a pointer to an array of 200 chars and the compiler now knows how far to step each index of a