Why first code output is false and true in second code? [duplicate] - c

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.

Related

Am I 'C'eriously going insane? [duplicate]

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.

static array changing its sizes in c while coping string [duplicate]

This question already has answers here:
Array index out of bound behavior
(10 answers)
Closed 2 years ago.
the code written below copies string from one array to another and i have declared the both arrays as static and i have given the size of the second array as '1' while the string size which is to be copied is greater than the size i have provided to the second array,still the program is running without any error and also coping the whole sting string and displaying it. if both the arrays are static then the size of second array 't' is increasing so that the it can holds the whole string.
#include<stdio.h>
void main()
{
char c[]="hello";
char t[1];
int i;
for(i=0;c[i]!='\0';i++)
{
t[i]=c[i];
}
t[i]='\0';
printf("%s",t);
}
then the size of second array 't' is increasing
No. The size is not increasing. You wite to the outside of the bounds of the array, and then read out of bounds and the behaviour of the program is undefined.
P.S. The program is ill-formed because main does not return int as is required.
if it is a an undefined behaviour then how the code is working and producing valid output
Because it is undefined behaviour. Any behaviour is possible when it is undefined. You cannot assume that the output wouldn't be valid because that is not guaranteed. Nothing is guaranteed when behaviour is undefined.

Why is this If statement not executing the code? [duplicate]

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){
...
}

Modifying a char array inside a function in C [duplicate]

This question already has an answer here:
Is modification of string literals undefined behaviour according to the C89 standard?
(1 answer)
Closed 7 years ago.
So I've been playing around with C lately and have been trying to understand the intricacies of passing by value/reference and the ability to manipulate a passed-in variable inside a function. I've hit a road block, however, with the following:
void modifyCharArray(char *input)
{
//change input[0] to 'D'
input[0] = 'D';
}
int main()
{
char *test = "Bad";
modifyCharArray(test);
printf("Bad --> %s\n", test);
}
So the idea was to just modify a char array inside a function, and then print out said array after the modification completed. However, this fails, since all I'm doing is modifying the value of input that is passed in and not the actual memory address.
In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?
In short, is there any way I can take in a char *input into a function and modify its original memory address without using something like memcpy from string.h?
Yes, you can. Your function modifyCharArray is doing the right thing. What you are seeing is caused by that fact that
char *test = "Bad";
creates "Bad" in read only memory of the program and test points to that memory. Changing it is cause for undefined behavior.
If you want to create a modifiable string, use:
char test[] = "Bad";

Character array Assignment [duplicate]

This question already has answers here:
Assigning strings to arrays of characters
(10 answers)
Closed 9 years ago.
int main()
{
char s[]="stack";
s="overflow";
}
This is not allowed.Its gives an error.But below code works fine.
int main()
{
char s[]="stack";
strcpy(s,"overflow");
}
Why this happens?
The variable s represents a pointer to the string. More specifically, it refers to the memory address of the first letter in your string "stack". Due to this reason, the operation s="overflow" makes no sense. How can you set the value of s (a pointer) to a string?
Keep in mind that C is a very low-level language, so you have to be wary of things that might seem intuitive to you not behaving the way you expect them to.

Resources