C string arrays using pointers and dynamic memory
#include <stdio.h>
#include <fstream> // ofstream ifstream
#include <iostream>
#include <cstring>
//#include <algorithm> //count
using namespace std;
unsigned int filesize(const char* fname){
ifstream f(fname);
string dummy;
unsigned int lines=0;
/*
//-------------------
while( getline(f, dummy) )
{
lines++;
}
//-------------------
*/
char c;
while ( !f.eof() )
{
c = f.get();
if ( c == '\n' )
lines++;
}
//-------------------
//count requires algorithm
//lines= count(istreambuf_iterator<char>(f), istreambuf_iterator<char>(), '\n');
//-------------------
f.close();
cout<<lines<< " lines in file "<<fname<<endl;
return lines;
}
int main(){
string s;
unsigned int c=0;
const unsigned int lines = filesize("fruit.txt");
char** v;
v = new char* [lines];
ifstream inf("fruit.txt");
while ( getline(inf,s) )
{
v[c] = new char [s.size()+1]; // +1 for null byte .c_str()
//strncpy(v[c], s.c_str(), s.size()+1);
strcpy(v[c], s.c_str());
c++;
}
cout << "v = "<<v<<endl; //memory address
cout << "v[0] = "<<v[0]<<endl; // first line
cout << "v[0][0] = "<<v[0][0]<<endl; //first char of first line
cout<<c<<endl;
for (unsigned int x=0; x<c; x++)
{
printf("%s\n", v[x]);
delete[] v[x];
v[x]=nullptr;
}
delete[] v;
v=nullptr;
return 0;
}
Struct pointers and arrow operator
#include <iostream>
using namespace std;
struct Movie {
string title;
int year;
};
int main (){
string s;
Movie a;
Movie* p;
//p = &a;
p = new Movie;
a.title = "Star Trek";
(*p).title="Star Wars";
(*p).year=1977;
cout << p->title <<endl;
cout << (*p).year << endl;
p->title="Indiana Jones";
p->year=1990;
cout << p->title <<endl;
cout << p->.year << endl;
delete p;
return 0;
}
Void pointers
#include <iostream>
using namespace std;
//void* is a pointer with no type
//void* can not be dereferenced
void foo(void* v){
//cout << *v <<endl; //cannot dereference a void pointer
int* p= (int*)v; //cast v into a int*
//double* p= (double*)v;
cout << *p <<endl;
}
int main(){
int i(3);
double d(4.9);
foo(&i);
//foo(&d);
return 0;
}
Function pointers
#include <stdio.h>
#include <iostream>
using namespace std;
int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int divi(int a, int b);
int main(void){
int(*q)(int, int) = ∑
cout << (*q)(3,4) <<endl;
/*
int(*p[4]) (int , int );
p[0] = ∑ // address of sum()
p[1] = &subtract; // address of subtract()
p[2] = mul; // address of mul()
p[3] = divi; // address of div()
*/
int(*p[4]) (int , int )= { sum, subtract, &mul, &divi };
int i, j;
printf("Enter two numbers: ");
scanf("%d %d", &i, &j); //like cin>>i cin>>j
for (int x=0 ; x<4; x++)
{
cout<< (*p[x])(i,j) <<endl; //call functions through pointer
}
return 0;
}
int sum(int a, int b){
return a + b;
}
int subtract(int a, int b){
return a - b;
}
int mul(int a, int b){
return a * b;
}
int divi(int a, int b){
if(b)
return a / b;
else
return 0;
}