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.
Related
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:
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){
...
}
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.
Perhaps an odd question..
I'm currently struggling to understand why the following equates to true i.e. "Hello World" is printed to the console? I've always thought that string comparison in C had to be done using strcmp or similar.
char *a = "Hello";
char *b = "Hello";
if(a == b)
{
printf("Hello World\n");
}
I also thought that this would only equate to true if the addresses were equivalent? Is it the fact that they're literals?
PS. Yes, this is scarcely related to an assignment, but I've just come up with the above off the top of my head. - this doesn't answer the assignment in any way.
The language makes no requirements where and how string literals are stored. All you know is that they have static storage duration and that you mustn't attempt to change the data. Nothing in the standard requires that two different string literals have different addresses, and it's entirely plausible that an implementation would deduplicate string literal data.
On the other hand, nothing requires that two identical string literals be stored at the same address, so there's little point in comparing addresses. Use strcmp for comparing the content of strings, always.
Identical literals that you put directly into the code will actually be pointed at the same memory location for optimization purposes.
The compiler in this case puts down "Hello" once in fixed memory, then points a and b at that memory.
For a more detailed understanding of what's going on, I suggest you compile this program (add a bunch of string literals first), then use gdb or valgrind or any other memory inspector and manually take a look at the memory pointing to string literals -- you'll find in standard cases gcc puts all the string literals together in memory and re-uses identical string literals.
a and b are pointers to characters.
A pointer basically stores a memory address. your a and b variables don't save the word "hello", but they save the memory address at which the word "hello" is saved.
print a and b in your program to see their value.
it will look like: 632176 or something like that, and they will be equal.
so the code a == b basically says: "Do a and b point to the same memory address?". And they do, because "hello" is a constant string and it's only going to be written to memory once.
I believe if you have two pointers who point to a value that is the same the compiler will just point both pointers at the same piece of memory. Its more efficient. But in C always use strcmp even in these kind of instances.
Whats happening here is that you have two pointers, called *a and *b. Next, as you know a pointer points a specific memory location. Now, when both *a and *b are set equal to the exact same sentence, it follows that a and b are pointing to a memory address. However, the compiler notices the pointers are the same sentence, so it sets them pointing to the exact same memory address for optimization purposes.
Because of this, what happens is something like this:
a = 0xFFFFFFFF;
b = 0xFFFFFFFF;
if(0xFFFFFFFF == 0xFFFFFFFF){
// Code
}
Now when you compare them, the compiler sees it as (0xFFFFFFFF == 0xFFFFFFFF) The compiler sees that they are equal, resulting in the if statement becoming true and showing Hello, World
However, this may not happen with different compilers, so you may get different results across compilers. This behavior does work with gcc though. So in that case, you should always use strcmp for comparisons to avoid random behavior like this.