Segmentation fault for Using Array - c++

If I write as following, Segmentation fault occurs. But if I write printf(messages[0]) or printf(messages[1]), I don't have error. WHY? I wanted to print all members of array using "for".
void givetag(char *array[]); //define function
int main()
{
char* messages[3];
givetag(messages); //sub function
int i;
for(i=0;i<3;i++)
{
printf(messages[i]);
}
}
void givetag(char *array[])
{
int i;
for(i=0; i<3; i++)
{
array[i]= (char*) malloc(10);
scanf("%s", array[i]);
}
}

#include <stdio.h>
#include <stdlib.h>
void
givetag(char *array[])
{
int i;
for(i=0; i<3; i++){
array[i]= (char*) malloc(100);
scanf("%s", array[i]);
}
}
int main()
{
char* messages[3];
givetag(messages); //sub function
int i;
for(i=0;i<3;i++) {
printf(messages[i]);
}
printf("\n");
return 0;
}
as you see in picture of out put, you must add malloc size (i change code).

Related

Merging two arrays in ascending order

I know the logic how to merge two arrays but the problem is how to code.
This was my code n it is giving correct ans but my sir told me that do it again,please tell me what I have to add in this code,
#include<iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
mergeArrays(arrayA,size1,arrayB,size);
}
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i];
cout<<" "<<array3[k];
}
int j=0;
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++)
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j];
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++];
}
}
I had searched this in many places but could not corrected my code
I had written this code but it is not giving correct ans.
#include<iostream>
using namespace std;
int merge(int *a,int *b,int aSize,int bSize);
int main()
{
const int aSize={8};
const int bSize={12};
int arrayA[aSize]={10,25,37,49,50,51,55,60};
int arrayB[bSize]={2,5,26,27,29,32,40,45,70,80,90,95};
merge(arrayA,arrayB,aSize,bSize);
return 0;
}
int merge(int *a,int *b,int aSize ,int bSize)
{
int cSize=aSize+bSize;
int *c=new int[cSize];
int j=0,k=0;
int i=0;
while(i<=aSize&&j<=bSize )
{
if(a[aSize ]<=b[bSize])
{
c[k]=a[aSize];
k++;
i++;
}
else
{
c[k]=b[bSize];
k++;
j++;
}
}
for(int i=0;i<k;i++)
{
cout<<c[i]<<endl;
}
delete[]c;
return c[k++];
}
your sir request you do Merging two arrays in ascending order. so i think you should return a new array, fill with array1 and array2's element, and the elements should be ascending order. here is a implement.(suppose your input arraies is already in ascending order.)
#include <iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2, int outArray[]);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
int outArray[size1+size];
int len = mergeArrays(arrayA,size1,arrayB,size, outArray);
cout <<" "<< len;
for (int i = 0; i< size1+size; ++i){
cout <<" " << outArray[i];
}
}
int mergeArrays(int array1[], int size1, int array2[], int size2, int outArray[])
{
int i=0, j=0, k=0;
int retSize = size1+size2;
while (k<retSize){
if (i==size1){// only left array2, copy it
for (; j<size2; ++j){
outArray[k++] = array2[j];
}
}else if (j == size2) { // only left array1, copy it
for (; i<size1; ++i){
outArray[k++] = array1[i];
}
}
else if (array1[i] > array2[j]){ // copy the min value to outArray
outArray[k++] = array2[j++];
}else{
outArray[k++] = array1[i++];
}
}
return k;
}
now, let's look at your first code:
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i]; // k is not changed, so you just assign array1's each value to array3[0]
cout<<" "<<array3[k];
}
int j=0;
// what's the purpose of this loop?
// and in loop, you don't use i, you just repeat set array3[0] = array2[0]!!
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++) // if array2's length bigger than array1's, will enter this loop.
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j]; // this just repeat assign array2's each value to array3[i]!!
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++]; // you delete array3, but at here you access it!! this will crash!
// also, in this for i loop, you have return, so it will only execute once.
}
// reach function end and no return if not enter for loop.
}
I haven't looked at your second code. I think you still need to do more study.

C++ void reverse function

We are converting base 10 to a number in a different base(B). I am having trouble with the void reverse function it will not reverse the order of the numbers.
string convertToBaseB(int num, int b){
int digit;
stringstream answer;
string x="";
while(num>0){
digit=num%b;
num/=b;
answer<<digit;
}
return answer.str();}
void reverse(int x[],int size){//reversing the
for(int k=0; k<size/2; k++){
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;}
}
Your reverse function works fine. However it doesn't looks like C++ to me... In C++ I would have a vector and do:
std::vector<int> arr;
//... fill arr
std::swap_ranges(&arr[0], &arr[arr.size()/2], arr.rbegin());
If you want to stick with your for loop, at least use std::swap like this
void reverse(int x[],int size) {
for(int k=0; k<size/2; k++)
std::swap(x[k], x[size-k-1]);
}
Works for me:
#include <iostream>
using namespace std;
void reverse(int x[],int size)
{
for(int k=0; k<size/2; k++)
{
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;
}
}
int main()
{
const int sz = 9;
int* digits;
digits = new int[sz];
for (int i=0; i < sz; ++i)
{
digits[i] = i;
}
reverse(digits, sz);
for (int i=0; i < sz; ++i)
{
cout<<digits[i]<<" ";
}
cout<<endl;
}

Get the SUM of array (C++)

I need to calculate numbers from the array.
I have a code written but I don't know how exactly I would need to write that I could get a summation of the numbers in the array.
If You would recommend some good material to learn something like so of, I would be thankful.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int n;
int array_1[20];
const char D[]= "Data.txt";
const char R[]="Rezults.txt";
void to_read ( int &n, int array_1[])
{
ifstream fd(D);
fd>>n;
for (int i=0; i<n; i++)
fd>>array_1[i];
fd.close();
}
int to_sum()
{
int m=0;
for (int i=0; i<n; i++)
m=m+array_1[i];
return m;
}
void to_print(int n, int mas_1[])
{
int sum=0;
ofstream fr(R);
fr<<n<<endl;
for (int i=0; i<n; i++)
fr<<array_1[i]<<" ";
fr<<endl;
sum=to_sum();
fr<<sum<<endl;
fr.close();
}
int main()
{
to_read(n, array_1);
to_sum();
to_print(n, array_1);
return 0;
}
I rewritten your code, removed global variables, changed formatting for easier reading, rename some variables to more explain for what they are and add function prototypes. Hope this will help you a little.
There are still lot of places which should be changed, but i want to keep as close to your original code as possible.
If you have any questions feel free to ask.
#include <iostream>
#include <fstream>
using namespace std;
//functions prototypes (these will be moved to header file if you wanna use this code from another file)
void to_read(int &len, int * array, const char * name); //added name parameter to avoid glogal variables
void to_print(int len, int * array, const char * name);
int to_sum(int len, int * array); //added parameters to avoid global variables
int main()
{
int lenght = 20; //moved to here, try to avoid global variables
int array_1[lenght]; //preconfigured size depend on variable
const char D[] = "Data.txt";
const char R[] = "Rezults.txt";
to_read(lenght, array_1, D);
//to_sum(lenght, array_1); //not needed here, not storing/processing result
to_print(lenght, array_1, R);
return 0;
}
void to_read(int &len, int * array, const char *name)
{
int lenght;
ifstream fd(name); //you should check if opening was successful
fd >> lenght; //you should check if reading was successful
if (lenght < len) len = lenght; //to prevent overflow of array, read max 20
for (int i=0; i<len; i++){
fd >> array[i];
}
fd.close();
}
int to_sum(int len, int * array)
{
int sum=0;
for (int i=0; i<len; i++){
sum += array[i]; //changed sum = sum + value; to sum += value; its same but this is more often used
}
return sum;
}
void to_print(int len, int * array, const char *name)
{
int sum = to_sum(len, array);
ofstream fr(name);
fr << len << endl;
for (int i=0; i<len; i++){
fr << array[i] << " ";
}
fr << endl;
fr << sum << endl;
fr.close();
}

How to debug this code for splitting an array by space?

I need to write a program that get a sentence and split its words by a delimiter(space);so I've wrote the code below but it doesn't seem to be working properly.
any idea's how to debug this code?
thanks in advance for your help.
here's what I come up with so far:
#include <iostream>
using namespace std;
const int BUFFER_SIZE=255;
int main()
{
char* buffer;
buffer=new char[255];
cout<<"enter a statement:"<<endl;
cin.getline(buffer,BUFFER_SIZE);
int q=0, numofwords=1;
while(buffer[q] != '\0'){
if(buffer[q]==' ') numofwords ++;
q ++;
}
char** wordsArray;
wordsArray= new char* [numofwords];
int lenofeachword=0, num=0;
int* sizeofwords=new int [numofwords];
for(int i=0;i<q;i++){
if(buffer[i]==' ')
{
sizeofwords[num]=lenofeachword;
wordsArray[num]=new char[lenofeachword];
num++;
}else{
lenofeachword++;
}
}
sizeofwords[num]=lenofeachword;
wordsArray[num]=new char[lenofeachword];
int k=0;
for(int i=0; i<numofwords;i++){
for(int j=0;j<sizeofwords[i];j++)
{
wordsArray[i][j]=buffer[k];
k++;
}
k++;
}
for(int i=0; i<numofwords;i++){
for(int j=0;j<sizeofwords[i];j++)
{
cout<<wordsArray[i][j];
}
cout<<endl;
}
}
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main() {
int size, j;
char s[1005];
gets(s);
scanf("%d", &size);
j=0;
for(int i=size; i<strlen(s); i+=size) {
for(; j<i; j++) {
printf("%c", s[j]);
}
printf(" ");
}
return 0;
}
You forgot to assign zero to lenofeachword after you deretmine lenght of a word. And if int main(), you should return an int value.

Cannot find logical error in C++ program

I am making a timetable generator as a project.
A part of the code seems to have a logical error.
void _tmain(int argc, _TCHAR* argv[])
{
int time=4;
int classes=2;
int teacher=4;
const int column=4;
const int rows=8;
int table[rows][column];
int final_table[rows][column];
int cell;
int temp=time;
int temp2=classes;
int temp3=teacher;
int cell_reset=111;
int cell_temp;
int k=0;
int selector_temp=0;
int selector_temp2=0;
cell=111;
//array initilization loop
for(int i=0;i<rows;i++)
{
for(int j=0;j<rows;j++)
{
table[i][j]=-1;
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<rows;j++)
{
final_table[i][j]=-1;
}
}
//Number generator loop
for(int i=0;i<rows;)
{
while(k<classes)
{
for(int j=0;j<column;j++)
{
table[i][j]=cell;
cell++;
}
cell=cell_reset+10;
k++;
i++;
}
k=0;
cell=cell_reset+100;
cell_reset=cell;
}
//selector loop
int counter=0;
for(int i=0;i<rows;i++)
{
counter=0;
for(int j=0;j<column&&counter<1;j++)
{
if(table[i][j]==selector_temp+10)
{
table[i][j]=-1;
}
if(table[i][j]==selector_temp-10)
{
table[i][j]=-1;
}
if(table[i][j]!=-1)
{
selector_temp=table[i][j];
final_table[i][j]=table[i][j];
for(int gg=(j+1);gg<column;gg++)
{
table[i][gg]=-1;
}
selector_temp2=selector_temp;
while(k<time)
{
selector_temp2+=100;
for(int ii=0;ii<rows;ii++)
{
for(int jj=0;jj<column;jj++)
{
if(table[ii][jj]==selector_temp2)
{
table[ii][jj]=-1;
}
}
}
k++;
}
k=0;
counter++;
}
}
}
//display loop
for(int i=0;i<rows;i++)
{
for(int j=0;j<column;j++)
{
cout<<final_table[i][j];
cout<<" ";
}
cout<<endl;
}
}//end of main bracket
This code generates exactly what I want.
But when I try to run this code the compiler gives me error that
Stack around the variable table is corrupt.
I choose to ignore this error and then the program gives me the correct result.
I have tried to find the source of this error but I cannot on the top of that I am getting correct results so if it cannot be found how can I disable the prompt that the compiler gives me.
The two initialisation loops are wrong - the inner loop should have j<column