I am trying to compare 2 strings using the below code:
char a[100] = "\0";
char* b[10];
for (int i = 0; i < 10; i++)
b[i] = "";
b[0] = "xy";
a[0] = 'x';
a[1] = 'y';
int c = strcmp(a, b[0]);
I think both a and b[0] contain the string "xy", so I expect int c equal 0. However the result stored in int c is -858993460.
Why would that happen? What should I do in order to avoid this fault? Thank you very much.
Update: I found that there is some error on my computer...
char a[3] = { NULL };
char d[3] = { NULL };
a[0] = 'x';
a[1] = 'y';
a[2] = '\0';
d[0] = 'x';
d[1] = 'y';
d[2] = '\0';
int c = strcmp(a, d);
Even using this code, I got int c to be a negative value. I have no idea why that happened.
It is undefined behaviour because a is not null terminated. All string in C have to be null terminated to be used in strcmp. What strcmp does is looping over the two strings until either one of the two is NULL terminated (see Implementation of strcmp to get an idea of how it works).
You can see that if '\0' is not present anywhere you got a problem there.
Read Why do strings in C need to be null terminated? for more info:
Related
Edit. Sorry for the minimal information included previously
Say I have the following code:
char ** a[16];
a[15] = '\0';
int i;
for (i = 0; i < 5; i++) {
char * b[3];
b[2] = '\0';
b[0] = "foo";
b[1] = "bar";
if (i == 4) {
b[0] = "hello";
b[1] = "world";
}
a[i] = b;
}
Straight after the for loop, if I include the following two lines:
printf("%s %s\n", a[0][0], a[0][1]);
printf("%s %s\n", a[4][0], a[4][1]);
I want the output to be:
foo bar
hello world
However it is instead:
hello world
hello world
I am aware this is because of my declaration, a[i] = b;, where b is an array of char pointers. Each loop, the character pointers pointed to by b[0] and b[1] are changed.
In the final loop they are set to "hello" and "world" respectively. Since I assigned b to a[i], every index of a now points to the same thing.
What I would like to do is dereference b, such that a[i] is given the value b points to rather than b itself. Therefore after the loop all indexes of a are not the same.
I tried using the following but both resulted in segmentation faults:
*a[i] = *b
and
**a[i] = **b
Any help would be much appreciated, as I'm totally lost. Thank you :)
What I would like to do is dereference b, such that a[i] is given the value b points to rather than b itself. Therefore after the loop all indexes of a are not the same.
Note that b itself is an array, so you cannot just assign value b points to rather than b itself because b does not point to a single value.
To really do this (not sure why you would want this) replace the line:
a[i] = b;
a[i][0] = b[0];
a[i][1] = b[1];
a[i][2] = b[2];
I got the char array "anana" and I am trying to get a "B" into the beginning in the char array so it spells "Banana" but I cannot wrap my head around how to construct a simple while loop to insert the B and then move every letter one step to the right
Assuming:
char array[7] = "anana";
Then:
memmove(array+1, array, 6);
array[0] = 'B';
The memmove function is specifically for cases where the data movement involves an overlap.
You can use a more traditional approach using...
#include <stdio.h>
int main()
{
char s[] = "ananas";
char b[7] = "B";
for(int i = 0; i < 7; ) {
char temp = s[i++];
b[i] = temp;
}
printf("%s", b);
return 0;
}
Please follow these steps:
Create a new array of size 7 (Banana + terminator). You may do this dynamically by finding the size of the input string using strlen().
Place your desired character say 'B' at newArray[0].
Loop over i=1 -> 7
Copy values as newArray[i] = oldArray[i-1];
I'm working on a C program and i am struggling with it (I've been spoiled by the concept of object orientation).
What i want to do is this:
I want to put values in a char array into an int. So for example i have char[0] == '1' and char[1] == '2'. I want to put these values in an int variable so its value is 12. I have tried looking but I am not sure how to get this done.
I really am poor at explaining so please ask for more info if necessary.
If your char array is made with characters '1' and '2':
char a[2];
a[0] = '1';
a[1] = '2';
int b = (a[0]-'0')*10 + (a[1]-'0');
If your char array is made with numbers 1 and 2:
char a[2];
a[0] = 1;
a[1] = 2;
int b = a[0] * 10 + a[1];
also, see: Why does subtracting '0' in C result in the number that the char is representing?
If the character array contains a string that is if it is zero-terminated then you can apply standard C function atoi declared in header <stdlib.h>.
For example
char s[] = "12";
int x = atoi( s );
If the array is not zero-terminated as
char s[2] = "12";
then you can convert its content to an integer manually.
For example
int x = 0;
for ( size_t i = 0; i < sizeof( s ) / sizeof( *s ); i++ )
{
x = 10 * x + s[i] - '0';
}
What you are trying to do is called parsing. In c this can be done with the atoi() function like this:
char s[] = "12";
int num = atoi(s);
I have the following C Code
#include <stdio.h>
int main(void){
char c[] = "ABC"
printf("%s ", c);
c[1] = 'B';
printf("%s", c);
return 0;
}
The output I want is ABC BBC but the output I get is ABC ABC. How can I replace the first character in an String / char array?
Indexing in C arrays start from 0. So you have to replace c[1] = 'B' with c[0] = 'B'.
Also, see similar question from today: Smiles in output C++ - I've put a more detailed description there :)
Below is a code that ACTUALLY WORKS!
char * replace_char(char * input, char find, char replace)
{
char * output = (char*)malloc(strlen(input));
for (int i = 0; i < strlen(input); i++)
{
if (input[i] == find) output[i] = replace;
else output[i] = input[i];
}
output[strlen(input)] = '\0';
return output;
}
C arrays are zero base. The first element of the array is in the zero'th position.
c[0] = 'B';
try
c[0] = 'B';
arrays start at 0
My head is getting bad trying to find a solution for this assignment because my ideas didn't work...
I have to interlace two char strings using pointers. See the following example (this example is not code):
char s1 = "My House Black"
char s2 = "Are very near"
Result: "MAyr eH ovuesrey Bnleaacrk"
How can I do this?
Try:
int total = strlen(char1) + strlen(char2);
int i1 = 0, i2 = 0;
for(i = 0; i < total; i++)
{
if(i % 2 == 0)
{
result[i] = char1[i1];
i1++;
}
else
{
result[i] = char2[i2];
i2++;
}
}
Here's a hint (pseudocode):
result = ""
for i = 0 to longest string's length:
result += some character (whose?)
result += another character (also, whose?)
Be careful: you need a little check somewhere, otherwise bad things might happen.
Since this is homework, I will just give you an outline.
First of all declare your two strings:
const char *s1 = "My House Black";
const char *s2 = "Are very near";
Next declare two pointers to char:
char *p1 = s1;
char *p2 = s2;
Now enter a while loop. The condition should be that *p1 or *p2 are not equal to zero.
Inside the loop output *p1 if it is not zero and then output *p2 if it is not zero. Increment each pointer if it refers to a non-zero character.
That's it, you are done!
Since this is tagged homework, I don't want to directly post code. But create three character arrays, one for each input, one long enough to contain the output, and traverse the input character arrays one character at a time (use pointer arithmetic). Store the character into your output string. Continue until you reach the end of each string. Don't forget the null terminations!
You need a target string that is large enough to hold both input strings and the string terminator.
Then you should probably use a loop (while or for) where you copy one character from each input string in each iteration.
For extra credits:
Consider the case where the input strings are of unequal length.
Is this what you want?
char * s1 = "My House Black";
char * s2 = "Are very near";
char * s = (char *)malloc(strlen(s1) + strlen(s2) + 1);
char * p1 = s1;
char * p2 = s2;
char * p = s;
while (*p1 && *p2)
{
*p++ = *p1++;
*p++ = *p2++;
}
while (*p1)
{
*p++ = *p1++;
}
while (*p2)
{
*p++ = *p2++;
}
*p = '\0';