This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I've checked all syntax.
#include <stdlib.h>
#include <stdio.h>
int main(){
char * response;
int anger = 0;
int correct = 0;
printf("type Dice");
scanf("%s", response);
if (response == "Dice"){
printf("Good Job!");
correct = 1;
}
}
I an trying to make a response generator and the is statement isn't working. I tried setting the variable response to the correct answer and the if statement worked so I was thinking that maybe something was wrong with my scanf. I'm a beginner in C.
You did char * response. This makes a pointer variable to a character. Right now it is not pointing to any memory(it is some garbage value). scanf stores user input in consecutive memory addresses starting from the one pointed by response. as response is uninitialised, the input may not necessarily be stored on the stack(Don't want that).
Now when you doresponse=="Dice" it doesn't mean anything at all.
Some pretty basic stuff on arrays and pointers and their comparison.
int arr[10];
now arr points to the first member of the array, arr+1 points to second, arr+2 to third and so on. arr[i] is a shorthand way of saying *(arr+i).
String is also an array of characters.
char *str1="Hello";
char *str2="Hello";
if(str1==str2){...}
What the if statement in line three here does is, it compares to pointers, ie it checks whether they both point to the same location. Since this is not true, execution won't go into the if block. What you want to do is compare the strings character by character. There is an inbuilt function in string.h called strcmp() which does that.
You can't use == to compare strings. Use strcmp() instead. If it returns 0, they're identical.
if (strcmp(response,"Dice")==0){
...
}
Related
This question already has answers here:
Addresses of two char pointers to different string literals are same
(10 answers)
Closed 2 months ago.
Ok so here we are comparing the memory location of the pointer to the string literal name[10] or Michael (or something like that)
char name[10]="michael";
char name2[10]="michael";
if (name == name2) { printf("ok\n");
printf("OKAF\n");
}
And of course if will evaluate to false and nothing happens, however:
char* name="michael";
char* name2="michael";
if (name == name2) { printf("ok\n");
printf("OKAF\n");
}
}
~
3rd example: (this one works as well)
char name="michael";
char name2="michael";
if (name == name2) { printf("ok\n");
printf("OKAF\n");
}
Here we are also comparing the memory location except in this case it evaluates to true?
My question is and I apologize in advance for my vapidity I'm a little confused as to why one works over the other; I have also seen implementations comparing two strings without using strcmp or the likes. What am I missing here can someone explain this to me in a language perhaps I can understand?
I've tried all 3 of those and 2 of the 3 of them evaluate to true as expected but I am still really confused as to why == with the IF statement in C is suppose to compare memory locations why using pointers or poorly initialized and defined chars work if its only suppose to compare memory locations.
First example: You are allocating two arrays pointing at two different locations in code. Result: The pointers are not equal.
Second: You have two distinct pointers that point to the same string.
The compiler MAY optimize these two strings, since they are actually the same, to be stored in the same region of the text part of your program, resulting in the comparison to be successful.
Third: You are not comparing memory locations, you are comparing characters, which just happen to be the same. However you should be getting a warning that you are assigning a const char * to a char.
This question already has answers here:
How to test for the end of a pointer array?
(3 answers)
How can I find the number of elements in an array?
(16 answers)
C: finding the number of elements in an array[]
(12 answers)
Closed 4 years ago.
is there any way to count the elements in an array of pointers to strings? with elements im refering to every word or phrase in it, here is an example of an array with 3 elements (each phrase in this case).
char *s[] = {
"To err is human...",
"But to really mess things up...",
"One needs to know C!!",
};
So here the array has 3 positions (that would be 3 elements), each pointing to a memory address which is the beginning of a String but it was still difficut to determine whether the array reached the end or not, so I added a fourth element '\0', so at the end it would have 2 null characters and then implemented this function.
int cantidadElementos(char *arr){
int count=0;
while(*arr!='\0'){
while(*arr!='\0'){
arr++;
}
arr++;
if(*arr!='\0'){
count++;
}
}
return count;
}
What I try to do is bound checking, so I figured out that if I use the address of each pointer in the array I could then see the address of the string, and then see if the last value is '\0' (to check if the string reached the end), but that could not be possible since the next memory address of the array could contain garbage values, so I camed up with adding another null character at the end of the array, and then checking if there is a double '\0'.
I just find this solution horrible (works, but still horrible).
This could suit for a text processor, since it is just 2 bytes more of memory that I would use to determine whether the text has reached end or not.
So going back to my question, is there any way to count the elements in an array of pointers to string? I have been searching a lot and couldn't came up with a better solution.
Test this:
const char *s[] = {"To err is human...", "But to really mess things up...", "One needs to know C!!"};
printf("%d\n",sizeof(s)/sizeof(*s));
Unlike arrays, there is no length information in pointers (which is what an array decays to when it is passed as an argument to a function, as you are doing with cantidadElementos). This is precisely why scalar strings are terminated with a null character in C; so that library functions can determine the length of the string and where to stop processing it.
To achieve the same thing with a pointer to pointers to strings, you could use a sentinel value like NULL at the end. Incidentally, this is also how the standard arguments to the main function work:
C Standard, ยง5.1.2.2.1.2:
If they are declared, the parameters to the main function shall obey the
following constraints:
โ argv[argc] shall be a null pointer.
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
Code 1
#include<stdio.h>
int main(){
const char st1[]={"Hello"};
const char st2[]={"Hello"};
if(st1==st2){
printf("True");
}
else{
printf("False");
}
return 0;
}
Code 2
int main(){
const char *st1="Hello";
const char *st2="Hello";
if(st1==st2){
printf("True");
}
else{
printf("False");
}
return 0;
}
Now in first code char array become const.
In the first code I got False as optput.
And in second code its true.
Thank in advance
== does not compare the string contents.
In the first snippet st1 are st2 char[6] types with automatic storage duration, and you are allowed to modify the string contents. When using == these types decay to char*. Their addresses must be different, so == will yield false.
In the second snippet, the string literals are read only, in C they are still formally char[6] (cf. C++ where they are const char[6] types) although the behaviour on attempting to modify the contents is undefined. Using const char* types for them is perfectly acceptable and reasonable. Because the contents are read only, the compiler might use the same string and so st1 and st2 might point to the same location in memory. In your case, that is happening, and the result of == is true.
The second is true because you are using an optimizing compiler. Since str1 and str2 are pointers, it makes them point to the same string, thus saving a little memory.
Totally wrong answer for both C and C++. Pls, vote for delete.
This question already has answers here:
Assigning strings to arrays of characters
(10 answers)
Closed 7 years ago.
Well first i'm using language c i still a beginner.
char S[20];
S ="ewer" ;
is that correct.
Arrays (including strings) can't be assigned in C. For strings you need strcpy, or preferably strncpy:
#include <string.h>
...
char S[20];
strcpy(S, "ewer"); // strcpy is fine for this example
strncpy(S, "ewer", sizeof(S)); // strncpy is safer in general and
// should be preferred over strcpy
No, that won't work.
The variable S is an array, and you can't assign to arrays like that in C. The string "ewer" is represented as an array of characters terminated by the character '\0'. To copy it into the array, you need to use a function:
strcpy(S, "ewer");
That's a good question. In fact, if you'd wrote char* S instead, the example would worked. You might be confused by the fact, that arrays and pointers have many alike things โ like [] operator.
But you must understand that array is different from a pointer. One of the main differences is that you couldn't increment an array, like ++myArr (this code okay for pointer, but not for an array). The other one you see in the question: you can not reassign an array variable to point another array. That is exactly what you're trying to do: you're assigning to the array variable S a pointer to a place with the text "ewer", that won't work.
Assuming that you wanted to assign to an array the text, you could do the following:
char S[] = "ewer";
Here you say to the compiler to allocate as much space on the stack, as the "ewer" text (plus the zero end character) holds, and copy that text there. Notice the empty braces [] โ you don't even need to manually count symbols, it would be done for you by a compiler.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change string literal in C through pointer?
Here is a code sample
void main()
{
char *i="prady"; printf("%c ",++*i);
}
Can anyone tell me why this code is giving a segmentation fault in gcc when I guess it should give 'q'. When I am using only *i++ it giving me the result but incase of pre-increment only it's giving me a segmentation fault.
Also tell me why void main is not a proper way to write main() function.
++*i means ++(*i). You're trying to modify the first character of a string literal, which is not permitted. As far as the C standard is concerned behavior is undefined, but this implementation has helpfully segfaulted to alert you to the problem.
*i++ means *(i++). You're modifying your pointer i, which is fine.
void main() is not a proper way to write a main function because the standard says that main returns int. The return value is used to indicate the success or failure of the program. Implementations can support other forms of main, but there are two that are required: int main(void) and int main(int argc, char *argv[]).
++*i
means that you pre-increment your pointer. for example
int *i
*i = 1;
imagine that i is a pointer to the address 0x8FF43FF0
if you compile ++*i before dereferencing i points to 0x8FF43F4
++(*i)
means, first dereference i, than increment
Steve Jessop already told you why ++*i returns an error so I'm not going to tell you that again.
*i++ will return p, the first letter of the word, because the "++" operator returns the value first, and only after had it returned the value does it increment it.
So if you want your program to print 'q' you would have to say printf("%c ",*i+1).
Also, if you want your program to print the second character, try: printf("%c ", *(i+1)). The next letter in the alphabet after the third letter of your word will be printf("%c ", *(i+2)+1) and so on.
Why you should use int main instead of void? The value returned by the main function informs the operating system about how the program ended. o (as in return 0) tells the operating system that the program had executed correctly. you usually use non 0 codes when the program must end because of an error.