This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have created two template project in Eclipse with CDT plugin(one is C project, another C++), and have compiled two very similar projects(as for me) but I get absolutely different console outputs. Why this outputs so different?
C code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
int n;
for (n=0; n<5; n++)
printf("%c ",numbers[n]);
return EXIT_SUCCESS;
}
output
some garbage
C++ code:
#include <iostream>
using namespace std;
int main() {
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << " ";
return 0;
}
output
10, 20, 30, 40, 50
You are printing int as char in C.
Change
printf("%c ",numbers[n]);
to
printf("%d ",numbers[n]);
You're trying to output the numbers as characters, causing your odd output.
The code worked fine for me as this.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
int n;
for (n=0; n<5; n++)
printf("%d ",numbers[n]);
return EXIT_SUCCESS;
}
Note the %d, rather than %c
You print the ASCII value of the integers. Try
printf("%i", numbers[n])
instead of
printf("%c", numbers[n])
You need %d to print integer and %c to print char in C
http://www.cplusplus.com/reference/cstdio/printf/
Look at your below statement
printf("%c ",numbers[n]);
You are using %c to print int, which is wrong.
To be specific printf has been borrowed from C and has some limitations. The most common mentioned limitation of printf is type safety, as it relies on the programmer to correctly match the format string with the arguments. The second limitation that comes again from the varargs environment is that you cannot extend the behavior with user defined types. The printf knows how to print a set of types, and that's all that you will get out of it. Still, it for the few things that it can be used for, it is faster and simpler to format strings with printf than with c++ streams.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Something wrong with my code, I want to multiply a string of numbers with an array of numbers(same length) and store the product in variable product, then I want to store this product of each column in my string variable (as a new values)
string var1 = "1232253759";
int arr[] = {5,3,7,1,2,8,9,2,2,1};
for(int i = 0; i < var1.size(); i++)
{
for(int n = 0; n < 10; n++)
{
int product = 0;
product = var1[i] * arr[n];
var1[i] = product;
}
}
there is a short output of this result:
245
-33
-231
25
50
400
-1008
32
So if im not mistaken this is what you want right.
where totalProduct will hold the product of every product and arr2 holds your columns. I added resultAsString so you have the result as string
note the var.at(i)-'0' which does the convertion you want or i think you are looking for.
for the conversion from int to string im using
std::stringstream ss;
ss << product;
a less C++ aproach would have been the atoi(product) function. or if using c++ 11 std:to_string(product)
Hope it helps
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string var1 = "1232253759";
int arr[] = {5,3,7,1,2,8,9,2,2,1};
int arr2[var1.size()];
int totalProduct = 0;
std::string resultAsString = "";
for(int i = 0; i < var1.size(); i++)
{
// for(int n = 0; n < 10; n++)
// {
int product = (var1.at(i)-'0') * arr[i];
// std::cout << product << "\n";
arr2[i] = product;
std::stringstream ss;
ss << product;
resultAsString += ss.str();
totalProduct += product;
//}
}
// for (int i = var1.size() - 1; i >= 0; i--)
// std::cout << arr2[i] << " ";
std::cout << resultAsString;
}
var1[i] is a char, not an int. char implicitly cast to int and calculation goes wrong. You need to map char with number to number itself ('1' -> 1, '2' -> 2). To do it subtract value of '0'. I.e. var1[i] - '0' it's number for char
The Counting sort below sorts elements based on their ASCII value.
The code below works fine but I want to do some I/O modification. The code doesn't take custom input.
I tried to do some changes but getting undefined behavior. My first doubt is why I'm getting undefined behavior. secondly, Please provide me with the code which will make the below code run as expected. The comment portion is what I tried by myself.I want it to take input from user.
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define RANGE 255
void countSort(char arr[]) //void countSort(char arr[],int n)
{
char output[strlen(arr)]; //char output[n];
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
for(i = 0; arr[i]; i++) {
count[arr[i]]++;
}
for (i = 1; i <= RANGE; ++i) {
count[i] += count[i-1];
}
for (i = 0; arr[i]; ++i) {
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
for (i = 0; arr[i]; ++i) {
arr[i] = output[i];
}
}
// Driver code
int main()
{
char arr[] = "geeksforgeeks";
countSort(arr);
cout<< "Sorted character array is "<<arr;
/*
int n;
cin>>n;
char arr[n];
for(int i=0;i<n;i++) {
cin>>arr[i];
}
countSort(arr,n);
for(int i=0;i<n;i++) {
cout<<endl<<arr[i];
}
*/
return 0;
}
So the OP asked, how to take an input from the user and sort this. And not a predefined string in a given char array.
I will give the answer. But the question is tagged with C++, and I will convert it to C++.
By the way. The code in the question is a one to one copy from GeeksforGeeks and tries to code the so called Counting Sort algorithm in C++ that is described here.
Since the code is taken from GeeksforGeeks I unfortunately need to blame user "rathbhupendra" for really bad C++ code. I am truly sorry.
The code is using:
C-Style arrays
Variable Length Arrays (Compiler extension. Not C++ compliant)
strlen
memset
#include<bits/stdc++.h> and #include<string.h>
using namespace std
unusal end conditions in for loops for(i = 0; arr[i]; ++i)
char arrays instead of std::strings
a Macro to define an array size (#define RANGE 255)
So, nothing C++.
And now, the answer.
You need to read the string from the user in a variable of type std::string with the function std::getline.
A std::string can be used like a character array. No difference.
Please see the C++ solution:
EDIT
Edited on the comments of MichaelDorgan
#include <iostream>
#include <string>
#include <vector>
constexpr size_t AsciiRange = 256;
// Convert signed char to unsigned size_t type.
inline size_t char2sizet(char c) { return static_cast<size_t>(static_cast<unsigned char>(c)); }
void countSort(std::string& stringToSort)
{
std::vector<size_t> count(AsciiRange, 0U);
size_t i { 0U };
for (i = 0U; i < stringToSort.size(); i++) {
count[char2sizet(stringToSort[i])]++;
}
for (i = 1U; i < AsciiRange; ++i) {
count[i] += count[i - 1U];
}
std::string output(stringToSort);
for (i = 0U; i < stringToSort.size(); ++i) {
output[count[char2sizet(stringToSort[i])] - 1U] = stringToSort[i];
--count[char2sizet(stringToSort[i])];
}
stringToSort = output;
}
int main()
{
std::cout << "\nPlease enter a string:\n\n";
// Get the string from the user
std::string inputString{};
getline(std::cin, inputString);
// Sort it by characters
countSort(inputString);
// Show result
std::cout << "\n\n\nString sorted by characters is:\n\n" << inputString << '\n';
return 0;
}
Hope this helps . . .
I geuss by 'getting undefined behavior' you meant segmentation fault which sometimes occured. The problem lies in this line
for(i = 0; arr[i]; i++)
instead you should write
for(i = 0; i < n; i++)
You can check that in the first case at the end of each loop arr[i] is sometimes some weird character(this character doesn't belong to the input string) and count[arr[i]] for this char returns negative number which produce segmentation fault here
output[count[arr[i]]-1] = arr[i];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am running below code and i am getting output as 8 0 4, rather 8 9 4. Can you please help me understand the problem with this code-
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *p;
p = (int*)calloc(2, sizeof(int));
*(p + 0) = 8;
*(p + 1) = 9;
p = (int*)realloc(p, 3);
*(p + 2) = 4;
for (int i = 0; i < 3; i++)
cout << p[i] << " ";
free(p);
p = NULL;
}
The realloc function needs the size on bytes and not elements.
You need to do
int *temp = realloc(p, 3 * sizeof(*temp));
if (temp == NULL)
{
// Handle error...
}
p = temp;
Note that I use a temporary variable for the result of realloc. This is because if realloc fails it will return NULL and reassigning the result back to the pointer you pass as the first argument then you will lose the original pointer.
The size specified as an argument to realloc() must be computed as a number of bytes. As you found out yourself, the simple fix is
p = (int*)realloc(p, 3 * sizeof(int));
Incidentally, you could use the type of *p instead of int to avoid potential inconsistencies if the type of p changes later:
p = (int*)realloc(p, 3 * sizeof(*p));
But since the cast is needed in C++, the inconsistency at least be visible.
You should also test whether calloc() and realloc() succeeded. They do not throw exception but return NULL when out of memory.
Note that you should decide whether you program in C or C++. These languages have a common ancestry but have diverged notably and some idioms used in one are considered bad style in the other, as more appropriate and safer constructs are available.
Here is a corrected version of your program in C:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = calloc(2, sizeof(*p));
assert(p != NULL);
*(p + 0) = 8;
*(p + 1) = 9;
p = realloc(p, 3 * sizeof(*p));
assert(p != NULL);
*(p + 2) = 4;
for (int i = 0; i < 3; i++) {
printf("%d ", p[i]);
}
putchar('\n');
free(p);
return 0;
}
While here is C++ program by PaulMcKenzie that implements the same thing, although the use of pointer p is still frowned upon:
#include <vector>
#include <iostream>
using namespace std;
int main() {
std::vector<int> pV(2);
int *p = pV.data();
*(p + 0) = 8;
*(p + 1) = 9;
pV.resize(3);
p = pV.data();
*(p + 2) = 4;
for (int i = 0; i < 3; i++) {
cout << p[i] << " ";
}
}
As you can see, std::vector<int>::resize() takes the number of elements, no need to compute byte counts.
Using pointers and especially pointer arithmetic is not good practice in C++, a much simpler version is:
#include <vector>
#include <iostream>
using namespace std;
int main() {
std::vector<int> v(2);
v[0] = 8;
v[1] = 9;
v.resize(3);
v[2] = 4;
for (int i = 0; i < 3; i++) {
cout << v[i] << " ";
}
}
You could also use an enumerator for the printout.
Ok, I got the problem:
p = (int*)realloc(p, 3);
the size value I had specified was 3, it should have been 3 * sizeof(int)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Why does the following code print out "0 0 0 0 0 0 0 "? I was expecting "1 3 6 10 15 21 28 ".
#include <iostream>
using namespace std;
void PrefixSum(float * input, float * output, int n){
float sum = 0;
for (int i=0;i<n;i++){
float value = input[i];
sum += value;
output[n] = sum;
}
}
int main(int argc, const char * argv[])
{
float input[] = {1,2,3,4,5,6,7};
float output[] = {0,0,0,0,0,0,0};
PrefixSum(input, output, 7);
for (int i=0;i<7;i++){
cout << output[i] << " ";
}
return 0;
}
Change output[n] to output[i] instead, you're not writing to any index in the array since output[7] is out of bounds. i is your loop counter not n
change
output[n] = sum;
to
output[i] = sum;
As everyone's pointed out, you're using n as the index instead of i, so you never modify any value within the array.
Writing loops is error prone, many of us will have made mistakes over the years. It's better to reuse existing code.
You're calculating the partial_sum. Using the standard library you could code it like this:
#include <iostream>
#include <numeric>
int main(int argc, const char * argv[])
{
using std::partial_sum;
using std::cout;
const int SIZE = 7;
float input[SIZE] = {1,2,3,4,5,6,7};
float output[SIZE] = {0,0,0,0,0,0,0};
partial_sum(input, input+SIZE, output);
for (int i=0;i<SIZE;i++){
cout << output[i] << " ";
}
return 0;
}
We can eliminate the loop printing out the result too:
#include <algorithm>
#include <iterator>
//...
using std::copy;
using std::ostream_iterator;
copy(output, output+SIZE,
ostream_iterator<float>(cout, " "));
And, finally, if you don't need the intermediate results array, we can just put the results straight to the ostream instead:
partial_sum(input, input+SIZE,
ostream_iterator<float>(cout, " "));
output[n] = sum;, n is 7 is out of output array boundary and you write data to it every time. Note, this is also undefined behavior. You are accessing float value = input[i]; right in for loop, so I guess that's just a typo.
update
output[n] = sum;
to
output[i] = sum;
Replace the 'n' with the 'i' in your for-iteration in PrefixSum ;)
I want to use the code below and I want to use it for "unknown size of input". For example there is an array int cac[1000][1000]. I can use vector<vector<int> > array;, then how can i initialize it with -1 ? Any suggestions?
#include <sstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <memory.h>
using namespace std;
int cac[1000][1000];
string res[1000][1000];
vector<string> words;
int M;
int go(int a, int b){
if(cac[a][b]>= 0) return cac[a][b];
if(a == b) return 0;
int csum = -1;
for(int i=a; i<b; ++i){
csum += words[i].size() + 1;
}
if(csum <= M || a == b-1){
string sep = "";
for(int i=a; i<b; ++i){
res[a][b].append(sep);
res[a][b].append(words[i]);
sep = " ";
}
return cac[a][b] = (M-csum)*(M-csum);
}
int ret = 1000000000;
int best_sp = -1;
for(int sp=a+1; sp<b; ++sp){
int cur = go(a, sp) + go(sp,b);
if(cur <= ret){
ret = cur;
best_sp = sp;
}
}
res[a][b] = res[a][best_sp] + "\n" + res[best_sp][b];
return cac[a][b] = ret;
}
int main(int argc, char ** argv){
memset(cac, -1, sizeof(cac));
M = atoi(argv[1]);
string word;
while(cin >> word) words.push_back(word);
go(0, words.size());
cout << res[0][words.size()] << endl;
}
What you can do is to use a associative array, where the key is a pair (rowPosition, ColumnPosition). When you want to set array[i][j] you just add or update the value assoArray[Pair(i,j)]. You can assume that any element which is not in the associative array has the initial value.
In general infinite multidimensional arrays are used for theoretical purpose.I hope i didn't misunderstood the question.
Using std::vector from the STL is much more straightforward than the following solution, which was pointed out in the comments for this post. I find that this site explains that topic effectively: http://www.learncpp.com/cpp-programming/16-2-stl-containers-overview/
An array of infinite size is not actually possible. However, you can achieve basically that effect using dynamic allocation. Here's some sample code:
int counter = 0;
int* myArray = new int[1000];
Fill the array with data, incrementing counter each time you add a value. When counter reaches 1000, do the following:
int* largerArray = new int[2000];
for( int i = 0; i < 1000; i++ )
{
largerArray[i] = myArray[i];
}
delete[] myArray;
myArray = largerArray;
With this method, you create the closest thing possible to an infinitely sized array, and I don't believe performance will be an issue with the copy piece