Could I get help finding the output of this function? (C++) - c++

What would the output of this code be, with all of the appropriate includes?
I understand what everything does up until *(x+4) = x[n];, and from there I got a little lost.
int main(){
int n;
char y[10] = "tasked";
char *x = y;
n = strlen (x);
*(x+4) = x[n];
x++;
printf ("%s",x);
}
Edit: I didn't understand what *(x+4) = x[n]; did to the string, thank you all!

The output of the program will be
ask
After this declaration
char y[10] = "tasked";
the array y is initialized the following way
char y[10] = { 't', 'a', 's', 'k', 'e', 'd', '\0', '\0', '\0', '\0' };
That is all characters that do not have a corresponding initializing character from the string literal are zero-initialized.
After this statement
n = strlen (x);
n is equal to 6.
So this statement
*(x+4) = x[n];
do the following. It substitutes the character 'e' (at index 4) for the character '\0' (at index 6);
So after that the array has the following content
{ 't', 'a', 's', 'k', '\0', 'd', '\0', '\0', '\0', '\0' }
Then the pointer advances one position and points to the second character of the array (with index 1) that is to the character 'a'.
So starting from this character 'a' until the terminating zero is encountered the characters 'a', 's', and 'k' are outputted.

Open this site : and paste your code, then add the following before the "int main()" line:
#include <string.h>
This will allow you to use the "strlen" function.
Click the green "Run" button to get the output.
Then follow #Vlad from Moscow's answer and you will be informed.

Related

What is the best way to decode a message given a hash function

I have a .txt file that has an encoded message, to decodde it you have to switch specific characters to a character in the alphabet. (It's like a letter x pointing to the letter y) then use it to decode the message from the .txt file.
I have the alphabet stored in a c-string:
const int ALPHA_SIZE = 26;
char alphabet[ALPHA_SIZE] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z' };
Then respectivelly the letters that correspond to the alphabet
char hashFunc[ALPHA_SIZE] = {'i', 'z', 't', 'o', 'h', 'n', 'd', 'b', 'e', 'q', 'r', 'k',
'g', 'l', 'm', 'a', 'c', 's', 'v', 'w', 'f', 'u', 'y', 'p', 'x'};
Now, my text file has this:
ifqkwxcadf ar cei fpoi masif cd cei xkdqirr du pxxnwafm pf pnmdkaceo cd p oirrpmi, teaqe rqkpohnir cei gpcp af ac-oplafm ac sikw gauuaqvnc pfg caoi qdfrvoafm, au fdc xkpqcaqpnnw aoxdrrahni, cd gigvqi cei dkamafpn masif dfnw cei ifqdgig gpcp. afxvcr cd cei pnmdkaceo cwxaqpnnw afsdnsi pggacadfpn riqkic gpcp qpnnig liwr, teaqe xkisifcr cei oirrpmi ukdo hiafm giqdgig-isif au cei pnmdkaceo ar xvhnaqnw lfdtf.
How do I correlate these 3 to give me the decoded message? I was thinking through switch statement but I'm sure there's other way more efficient than this. Thank you.
I always red-flag any question from a beginner programmer asking for "the best" way to do something.
But I am answering because a switch is definitely inappropriate for this, due to the amount of effort required to code it, and how annoyed I would be to encounter any code based on that approach.
The fact is, your problem is simply one of mapping. All you are doing is mapping one character to another. So just build a table. If you are on 99.9999% of modern computers, you'll be dealing with 8-bit characters (we should ignore UTF-8, but actually this will be compatible with UTF-8 too).
char encode[256], decode[256];
for (int i = 0; i < 256; i++) encode[i] = decode[i] = (char)i;
for (int i = 0; i < ALPHA_SIZE; i++) {
encode[(unsigned char)alphabet[i]] = hashFunc[i];
decode[(unsigned char)hashFunc[i]] = alphabet[i];
}
From there it should be obvious. All you need to do to encode or decode a character is to use that character's (unsigned) value to look up the corresponding table entry.
This method is probably the fastest basic approach. But it might not be the best for whatever your requirements are.
Disclaimer: I'm not a C++ programmer; I'm a C programmer. But this answer will work for both C and C++.
Instead of using array notation (i.e., with braces) for initializing your arrays, you should use actual C strings. That is:
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
char hashFunc[] = "iztohndbeqrkglmacsvwfuypxj";
(Your original hashFunc was missing j; I assume that's a transcription error. I added it at the end.)
This way, you can easily convert from one "alphabet" to the other:
void convert_alphabets (char * str, const char * from, const char * to) {
const char * found;
while (*str) {
found = strchr(from, *str);
if (found)
*str = to[found - from];
str ++;
}
}
(You'll need to include <string.h> to get strchr(), or <cstring> in C++ if you prefer the std:: namespaced version.)
This function merely looks up every character in the from string, and if it finds it, replaces it with the equivalent character in the to string (notice that found will point to the position where the character was found, and thus found - from will give you the index into the from string/array). You can call it with from = alphabet and to = hashFunc to encode, or vice-versa to decode.

Is there a way to initialize arrays with mixed chars and "strings"

I would want to initialize char array during compilation time with least amount of manual work.
Is there a working shorthand format for this
char arr[5] = {0x4, 'a', 's', 'd' 'c'};
such as
char arr[5] = {0x4, "asdc"};
You could integrate the char int the string with escape sequences:
char arr[6] = { "\x04asdc"};
edit: corrected the wrog length of the array.
No that's not possible. But you could do
char arr[] = "\04asdc";
The problem with this is that is would not be exactly like the original array you show, since it would include the string terminator and therefore have six elements.

How to point to N (runtime defined number) bytes in the middle of something bigger?

The case is that I have a big set of binary data loaded in memory and need to perform bitwise operations between a N bytes length block of data and a N bytes chunk from the middle of this big set.
My first thought is to somehow get a pointer to N chars and then change it to point to start of the chunk. Pseudo code for what I intended to do:
#include <iostream>
int main()
{
unsigned int n = getBlockLength(), x = getChunkStartPos(), s = getBinarySetLength();
char *binary_set;
char (*chunk_ptr)[n]; //Let's suppose n = 5
//char block[n] = {'s', 'm', 't', 'h', 'g'};
binary_set = malloc(s);
fillBinarySet(binary_set, s); //Let's suppose s = 15 and binary_set is now filled with {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'}
chunk_ptr = &binary_set + x;
std::cout << *chunk_ptr << std::endl; //should print "efghi"
//actually would do something like this:
//result = block & *chunk_ptr;
return 0;
}
This of course won't compile and the array of characters is just an example, as I did already said it would actually be a big set of binary data. Even if it would compile, I'm not sure of how system would know chuck_ptr points to n bytes (it searches for null character - that I can't put inside binary_set just for this purpose - when dealing with char, but what in the case of an array of bools?)...
By "big" I mean something between 125MB and 1000MB. It most likely will be just memory mapped (mmap()) from a file instead of fully loaded into memory but RAM consumption is expected to be almost the same, as entire set will be subject to frequent read and write operations. Referred block (and chunk) is supposed to be commonly between 1B and 5MB length.
Any thoughts on the fastest and less CPU and RAM intensive way to achieve this goal, please? This is the core of an already heavy application and the only working solutions (e.g.: looping over the binary data set byte by byte from start to the end of the chunk) I could develop don't suit performance requirements. :(
I just want some idea or direction, not asking you to do my job for me. If that is not possible with C or C++, I would like to get pointed to some solution in other high performatic, compiled, language. Thanks so much.

Word Search Puzzle: How do I search an array of letters to find a word?

I am trying to create a word-search puzzle game that asks the user to enter a word they think is in the array, and if that word is found, then give the user a point (for a total of 10 points, after which a congratulatory message is printed).
In this code I have a regular array but based on some research I think a 2D array might be better. What are your thoughts? Specifically I am interested in what kind of search algorithm I should consider
#include <iostream>
using namespace std;
int main() {
// your code goes here
cout<<"=================================================================================="<<endl;
cout<<"|| ||"<<endl;
cout<<"|| Welcome to the ECE 114 Game Design! ||"<<endl;
cout<<"|| ||"<<endl;
cout<<"=================================================================================="<<endl;
cout<<"This is a sample output"<<endl;
//We want to ask the user to enter a word that they think the cross-word puzzle contains
//if the puzzle contains that word, we tell the user they are correct and update their points
//score by 1. Total of 10 points to gain, when the points score reaches 10 the user gets congratulatory message
string myArray[] = { "A B C D E F G H
S P A D E T R Y
T I G O A L E A
T R A I N E A W
O A P B E A T N "};
//The first array above will just be a visual for the player to see
//This second array is the one that I will use to search for words
char wordBank[5][8] = [[ 'A', 'B ','C', 'D', 'E', 'F', 'G', 'H'],
['S','P', 'A', 'D', 'E', 'T', 'R', 'Y'],
['T', 'I', 'G', 'O', 'A', 'L', 'L', 'E', 'A'],
['T', 'R','A', 'I', 'N', 'E', 'A', 'W'],
['O', 'A', 'P', 'B', 'E', 'A', 'T', 'N']];
cout<<myArray<<endl;
return 0;
}
I suggest you add some additional variables to make searching easier. For example, create strings of the text in vertical and horizontal directions.
static const std::string puzzle_text[] =
{
"ABCDEFGH",
"SPADETRY",
"TIGOALEA",
"TRAINEAW",
"OAPBEATN"
};
int main(void)
{
std::string vertical_texts[8];
for (unsigned int column = 0; column < 8; ++column)
{
for (unsigned int row = 0; row < 5; ++row)
{
vertical_text[column] += puzzle_text[row].at(column);
}
}
return 0;
}
By creating the strings for the vertical letters, the std::string::find can be used. The vertical strings only need to be created once per puzzle.
Tasks for the OP: reverse search (see std::string methods), and diagonal string creation.
Edit 1: Search algorithm
Here is an algorithm that I use with searching these puzzles:
1. Extract first letter of key word.
2. Search text row for letter.
3. If letter is found, check neighboring letters for 2nd letter of key word.
3.1. If 2nd letter is found, continue in direction and search for remaining letters of keyword.
This has served me well, especially for difficult to find words.

Why the difference in size when declaring a string in C++?

I should know this, but I don't and I think its probably a major gap in my foundation knowledge so I thought I should ask the experts.
Given:
char s1[] = { 'M', 'y', 'W', 'o', 'r', 'd' };
char s2[] = "MyWord";
cout << strlen(s1)<<endl;
cout << strlen(s2)<<endl;
cout << sizeof(s1)<<endl;
cout << sizeof(s2)<<endl;
Why when declared as s1 is the strlen 9 but when declared as s2 is is 6? Where does the extra 3 come from, it it the lack of a null terminating character?
And I understand that sizeof(s2) is 1 byte larger than sizeof(s2) because s2 will have the null character automatically added?
Please be gentle, TIA!
char s2[] = "MyWord"; Auto adds the null terminator because of the "" declaration.
s1 declaration does not. When you do a strlen on s1 and it comes out to 9 it is because it eventually ran into a \0 and stopped. s1 shouldn't be used with strlen since it is not null terminated. strlen on s1 could have been 1,000. If you turn on memory violation detection strlen of s1 would crash.
The first one lacks the implicit \0 terminator present in the second. Thus:
The first is 1 less than the second, memory-wise
Doing strlen on the first is undefined behavior (since it lacks the terminator)
Lack of terminating null character as you say.
When the strlen function is called on s1, it counts the characters until it finds a terminating '\0'. You may have different result depending on how your memory is initialized.
Your definition of s2 is actually equivalent to
char s2[] = { 'M', 'y', 'W', 'o', 'r', 'd', '\0' };
s1 is only 9 by happenstance; you can only use strlen on terminated strings. Declare it as char s1[] = { 'M', 'y', 'W', 'o', 'r', 'd', '\0' }; and see what happens.
strlen(s1) can return any value > 6. because he is searching for the first '\0' char and you didn't provide it.
In your code,
s1 and s2 are arrays of char.
s1 last element is d, whereas s2 last element is \0.
That is, there is one more character in s2. It is a null-terminated string but s1 is not a null-terminated string.
Since s1 is not a null-terminated string, the expression strlen(s1) would invoke undefined behavior, as strlen will continue reading s1 beyond the last element.