I'm working through a demo program written by someone else, and I'm very confused about some of the statements they are using. I'm not very familiar with C++ (moreso with Obj-C) and I'm not sure if this is valid code or not. Take, for example, the following: (comments are mine)
int main(int argv, char** argc)
{
int perm [20]; //OK, so declare an array of ints, size = 20
for (int i=0; i < 20; i++)
perm = i; //whaaaaa??? thought you need to specify an element to assign to an array...
}
That is one example - my compiler throws an "incompatible types in assignment of 'int' to 'int [20]' error, but apparently others have been able to compile the program. Am I nuts, or is this bad code?
Here's another piece I just don't get:
int d[20] = {0}; //OK, another int array of size 20, initialized to 0's
for (int i = 1; i < n; i++)
{
d = d[i - 1]; //this I don't get - assign the array to one of its own elements??
if (invperm[i - 1] < b)
d++; //this would just increment to the next element?
}
I suspect the error is one of comprehension on my part, as if the code was bad other people would've commented on that fact...if anyone has a good explanation and/or resource I can read to understand this, I would be most appreciative!
Thanks!
*EDITED TO ADD*
In response to the answers below, I did copy/paste that code, and it looks intact to me...I can only assume when the original author posted it, it mangled it somehow. Thanks for the replies, I'm glad I had the right understanding, and I'll try and contact the author to see if there is an un-mangled copy out there somewhere!
All those examples are absolutely wrong. It looks like you lost [i] when you copied the code from wherever you got it from.
I have seen something similar with code sent over messenger programs that treat certain bits of text as emotes and replace them with images that don't get copied as text, but instead get dropped.
Your understanding is fine, that code is just entirely nonsensical.
d++; //this would just increment to the next element?
It would if d were a pointer. However since d is an array, it's simply illegal.
This is most certainly a copy/paste error.
I have succumbed to the temptation of copy/pasting code at one point during a game tech project involving Lua scripts. If the Lua script fails there is no feedback/output that indicates something is failed (which is very frustrating). After debugging for hours I realised my script was using 'smart quotes'.
Whilst this code is broken it can still teach you some things about C++.
int perm [20];
cout << endl << perm << endl;
cout << endl << &perm[0] << endl;
'perm' returns the memory address of the first element of the array. so when you are trying to assign 'i' to 'perm' in that main for loop (20 times) you will know now that you were trying to assign an integer to a memory address, hence the incompatible type error.
The second section however is verry broken and I can't discern much learning from this :P.
I added in an example program to show how pointers/arrays can be used:
#include <iostream>
using namespace std;
int main()
{
int d[20] = {0}; // 20 ints, set to 0
int * ptr = d; // points to d[0]'s memory address
for(int i = 0; i < 20; i++)
{
d[i] = 0 + i; // set array values
}
for(int i = 0; i < 20; i++)
{
// iterates through d and prints each int
cout << endl << "d[i]: " << d[i] << endl;
// dereferences the ptr to get the same int
// then incraments the position of the pointer for next time
cout << endl << "*ptr++: " << *ptr++ << endl;
}
getchar();
return(0);
}
Related
This is my first time asking something on stackoverflow, so I'm sorry if I fail in any aspect of building the topic etc...
So I'm a newbie at C++, I'm still at the beginning. I'm using a guide someone recommended me, and I'm stuck in a exercise which is about char and strings.
It's the following: They ask me to create a function that says the number of times that a certain word was repeated on a string.
I'll leave my code below for someone who can help me, if possible dont give me an obvious response like the code and then I just copy paste it. If you can just give me some hints on how to do it, I want to try to solve it on my own. Have a good night everyone.
#include <iostream>
#include <string.h>
#define MAX 50
using namespace std;
int times_occ(string s, string k) {
int count = 0, i = 0;
char word[sizeof(s)];
// while (s[i] == k[i])
// {
// i++;
// if (s[i] == '\0')
// {
// break;
// }
// }
for (i = 0; i <= sizeof(s); i++) {
if (s[i] == ' ' || s[i] == '\0') {
break;
}
word[i] = s[i];
}
word[i] = '\0';
for (i = 0; i <= sizeof(k); i++) {
if (word) {
if (k[i] == word[a]) {
a++;
count++;
}
}
}
cout << word << endl;
cout << count << endl; // this was supposed to count the number of times
// certain word was said in a string.
return count;
}
int main() {
char phrase[MAX];
char phrase1[MAX];
cin.getline(phrase, MAX);
cin.getline(phrase, MAX);
times_occ(phrase, phrase1);
}
Okay, first of all, the way you've used sizeof isn't really valid.
sizeof won't tell you the length of a string. For that, you want std::string::size() instead.
In this case, std::string is an object of some class, and sizeof will tell you the size of an object of that class. Every object of that type will yield the same size, regardless of the length of the string.
For example, consider code like this:
std::string foo("123456789");
std::string bar("12345");
std::cout << sizeof(foo) << "\t" << foo.size() << "\n";
std::cout << sizeof(bar) << "\t" << bar.size() << "\n";
When I run this, I get output like this:
8 9
8 5
So on this implementation, sizeof(string) is always 8, but some_string.size() tells us the actual length of the string.
So, that should at least be enough to get you started moving in a useful direction.
As #JerryCoffin mentioned, your word array has an invalid size. But - I want to make a more fundamental point:
Your code has two loops and a bunch of variables with arbitrary names. How should I know what's the difference between s and k? I even get k and i mixed up in the sense of forgetting that k is a string, not an integer. That kind of code difficult to read, and to debug. And we are a bit lazy and don't like debugging other people's code...
I suggest that you:
Have a very clear idea what your loops do, or what the different parts of your function do.
Create small self-contained functions - no more than one loop each please! - for each of those parts.
Use meaningful names for each function's parameters and for the local variables.
And then, if your program doesn't work - try debugging one function at a time.
I'm working on an exercise and can't seem to figure out what's going wrong. The prompt reads, "The variable cp_arr has been declared as an array of 26 pointers to char. Allocate 26 character values, initialized to the letters 'A' through 'Z' and assign their pointers to the elements of cp_arr (in that order)."
Edit: this post was flagged as a duplicate to a post involving pointers and strings, this isn't the same issue.
While testing the code, this is what I've come up with, but the output isn't exactly what I was expecting.
#include <iostream>
using namespace std;
int main()
{
char next = 'A';
char* cp_arr[26];
for (int i = 0; i < 26; i++)
{
cp_arr[i] = new char(next);
cout << cp_arr[i] << endl;
next++;
}
system("pause");
}
cp_arr[i] is a pointer-to-char, which is interpreted (by deeply-embedded convention) as a C string pointer. If you want to output just the one char it points to, do that:
cout << *cp_arr[i] << endl;
I have finished writing a program that included reversing, expanding and shifting arrays using the pointer requirement asked by the professor. Everything compiles but the answer from the expand function does not return what I wish: adding 0s after the old user input array which asks for the size of the array and the numbers you wish to put into the array. I think my problem may lie from the fact that I include a pointer on something that might not have a reference in the program. Below is my code:
// *numPtr refers to my old user input array and int tamaño is the size of the array
void expandArray(int *numPtr, int tamaño) {
int *nuevoArray = new int[tamaño *2];
for (int i = 0; i<tamaño; i++) {
nuevoArray[i] = numPtr[i];
}
for (int i = tamaño; i < (tamaño*2); i++) {
nuevoArray[i] = 0;
}
std::cout << nuevoArray << " ";
}
As I said, my theory of the code not compiling the way I wish is because I use the *nuevoArray and it has no reference in my main code, but then again, I am just a beginner with C++. I was thinking of just doing a vector, but I think I would not follow the pointer requirements placed by the professor.
If you want to print the contents of nuevoarray, just use a for loop like this:
for (int i = 0; i < (tamaño*2); i++) {
std::cout << nuevoArray[i] << " ";
}
std::cout << "\n";
Also, since you are using new[] to create the array, you should not forget to delete[] it!
you can print your array by using
for (int i = 0 ; i < tamano * 2 ; ++i) {
std::cout << nuevoArray[i] << " ";
}
std::cout << std::endl;
or in c++11
for (auto i : nuevoArray) {
std::cout << i << " ";
}
std::cout << std::endl;
PS: The std::endl will return to the start of the new line and flush the cout buffer.
Your code does appear to be allocating a larger array and correctly copying data from numPtr into the new array and also correctly filling the remainder of the new array with zeros.
You don't explicitly say what you expect this function to output, but I'm guessing you expect it to print out the contents of the new array, and that you believe there's a problem because instead of that, you're seeing it print something like "0x7fb46be05d10".
You're not correctly printing the array out. Instead you're printing the memory address of the first element out. If you want to see the contents, then you need to loop over the elements of the array and print each one out individually.
Here's a function showing one way of doing that:
#include <algorithm>
#include <iterator>
void printArray(int *arr, int n) {
std::copy(arr, arr + n, std::ostream_iterator<int>(std::cout, " "));
}
Now you can replace the line std::cout << nuevoArray << " "; in your existing code with printArray(nuevoArray, tamaño*2);
(Also it sounds like whoever is teaching you C++ should take a look at this presentation from the recent C++ conference, CppCon 2015: Stop Teaching C)
I am trying to output the values present in the array, that are accepted during runtime, onto the console. But when I run this program I get the 5 values in the array as the last value only.
For example: if i give 0 1 2 3 4 as the five values for this program then the output is shown as 4 4 4 4 4.
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int arrsize = 5;
int *ptr = new int[arrsize];
*ptr = 7;
cout << *ptr << endl;
cout << "enter 5 values:";
for (int i = 0; i < arrsize; i++)
{
cin >> *ptr;
cin.get();
}
cout << "the values in the array are:\n ";
for (int i = 0; i < arrsize; i++)
{
cout << *ptr << " ";
}
delete[] ptr;
cin.get();
return 0;
}
Both of your loops:
for (int i = 0; i < arrsize; i++)
...
loop over a variable i that is never used inside the loop. You are always using *ptr which refers always to the first element of the dynamically allocated array. You should use ptr[i] instead.
A part from that, dynamic allocation is an advanced topic. I'd recommend sticking with simpler and more commonly used things first:
std::cout << "Enter values:";
std::vector<int> array(std::istream_iterator<int>(std::cin), {});
std::cout << "\nThe values in the array are:\n";
std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
Live demo
Following issues I think you could tackle:
The first include can be omitted I think. Your code works without that.
You use cin.get(), not sure why you need that. I think you can remove that. Even the one at the very end. You could put a cout << endl for the last newline. I am using Linux.
And use ptr like an array with index: ptr[i] in the loops as mentioned in the other answer. ptr[i] is equivalent to *(ptr+i). You have to offset it, otherwise you're overwriting the same value (that is why you get that result), because ptr points to the first element of the array.
P.S.: It seems that if you're using Windows (or other systems) you need the cin.get() to avoid the console to close down or so. So maybe you'd need to check it. See comments below.
Again, I'm trying to make a simple program. It will read some kind of board, at the size of RxC. Each items on the board are letters, separated with spaces. This is a sample board:
A B C
D E F
G H I
After that, it will read an integer N, and for next N lines, read a string and process them one by one based on the given board. But now, I'm facing a problem with how to read them. Here is the code :
#include<iostream>
using namespace std;
int r,c,el; char **arr;
int main()
{
char *tes;
int n;
//start reading the puzzle
cin >> r >> c; el=r;
cout << el << endl;
arr = new char * [3*(r+c)-6];
for(int i=0;i<r;i++)
{
arr[i] = new char[c+1];
for(int j=0;j<c;j++) cin >> arr[i][j];
arr[i][c] = '\0';
}
for(int i=0;i<el;i++) cout << arr[i] << endl;
cin >> n;
while(n>0)
{
n--;
cin >> tes;
cout << tes << endl;
}
}
I don't know what's wrong with this, it's seems OK to me. However, it always get runtime errors. I'm using latest MinGW and gdb debugger. On gdb I saw something like
"received signal SIGSEGV. Segmentation
fault"
, and an 0xC0000005 error. I really have no idea what's going on here. I've tried both iostream(cin&cout) and cstdio(scanf,puts,etc.)
P.S.: I declare the variables globally, because I will process them on a different function out of the main() function. I set the size of the "height" of the array to (3*(r+c)-6), not to the normal (r) is because I will use the same array to store another strings later.
In addition to the problems already noted by others, you haven't allocated any memory for tes - it's just a dangling pointer.
Change:
char *tes;
to, e.g.:
char tes[80];
A board of size R*C needs, not very surprisingly, r*c chars of storage. I fail to understand why you're allocating the board in so many steps. A single char* board = new char[r * c]; should do it, then just keep track of where in the array your're reading.
Segmentation fault usually means you are trying to access memory which hasn't been allocated, for instance
char* mystr = (char*)malloc(3*sizeof(char));
mystr[4] = 0.0;
will (most likely) cause a seg fault because you're accessing memory which you didn't allocate (mystr goes from 0 - 2).
Are you sure you're allocating the memory correctly? I'm not sure why you have 3*(r+c)-6.
Further to unwind's answer, your array has size 3*(r+c)-6, but you are looping over values i = 0; i < r;, which depending on the values may just run out of bounds (plus it makes no sense).