Searching a word in a 2d array in c programming - strstr

I am trying to set up a program that when you type /s then a movie title (ex. /s Green Mile it searches for that movie title in the movies array but my strstr function is not working. Also /a adds movie /r shows all movies in database and /q quits program.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int i;
int j = 1;
int k = 0;
int counter = 0;
char buffer[64];
char buffer2[64];
int len;
do {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
if (buffer[1] == 'a') {
len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
for(i=3; i<sizeof(buffer); i++) {
movies[counter][k] = buffer[i];
k++;
}
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
k = 0;
}
if (buffer[1] == 'q') {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
}
if (buffer[1] == 's') {
for(i=2; i<sizeof(buffer); i++) {
buffer2[k] = buffer[i];
k++;
}
for (i = 0; i < counter; i++) {
if (strstr(movies[i], buffer2) != NULL) {
printf("Found %s in position %d,%s\n", buffer2, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
k = 0;
}
if (buffer[1] == 'r') {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", j, &movies[i][0]);
j++;
}
printf("\n");
j = 1;
}
} while (buffer[1] != 'q');
}

Revised code.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int counter = 0;
char buffer[64];
char * movieTitle = &buffer[3];
while(true) {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
//replace terminator every time
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
if(strstr(buffer, "/a") && counter < 1000) {
strcpy(movies[counter], movieTitle);
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
}
else if (strstr(buffer, "/s")) {
for (int i = 0; i < counter; i++) {
if (strcmp(movies[i], movieTitle) == 0) {
printf("Found %s in position %d,%s\n", movieTitle, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
}
else if (strstr(buffer, "/r")) {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", i + 1, &movies[i][0]);
}
printf("\n");
}
else if (strstr(buffer, "/q")) {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
break;
}
else {
printf("unrecognized command");
}
}
}

Related

Exception thrown at 0x7A12FF80 (ucrtbased.dll) in Project 3.exe: 0xC0000005: Access violation reading location 0x00000000

I have attempted to run this code. Prior to running this, no warnings or errors exist but once it is executed I have an exception thrown and it stops the program from compiling. Here is my code and the error is in the subject line. The CDA file is being used as header file to create a Circular Dynamic Array that is going to be manipulated in Heaps.cpp. The heaps.cpp is to create a binary heap that is to be used in to create Binomial heaps, but that code has not been developed yet.
#include <iostream>
using namespace std;
template <class T>
class CDA
{
private:
int rear;
int size;
int capacity;
T* circArray;
int front;
bool ordered;
T placeHolder;
public:
CDA();
CDA(int s);
~CDA();
int Front();
T Data(int n);
T& operator[](int i);
void AddEnd(T v);
void AddFront(T v);
void DelEnd();
void DelFront();
int Length();
int Capacity();
int Clear();
bool Ordered();
int SetOrdered();
int S01(int n);
T Select(int k);
void InsertionSort();
void QuickSort();
void QuickSort1(int low, int high);
void CountingSort(int m);
int Search(T e);
void reSize();
void Shrink();
int BinarySearch(int left, int right, T e);
int QSortPartition(int low, int high);
void Swap(int* x, int* y);
int QSelPartition(int front, int rear);
T QuickSelect(int front, int rear, int k);
CDA<T>& operator=(const CDA& a);
CDA(const CDA& old);
int Median(int low, int high);
};
template <class T>
CDA<T>::CDA()
{
capacity = 1;
circArray = new T[capacity];
size = 0;
rear = size - 1;
front = -1;
ordered = false;
placeHolder = 0;
}
template <class T>
CDA<T>::CDA(int s)
{
size = s;
capacity = s;
circArray = new T[capacity];
front = 0;
rear = size - 1;
ordered = false;
}
template <class T>
CDA<T>::CDA(const CDA& a)
{
size = a.size;
capacity = a.capacity;
circArray = new T[a.capacity];
front = a.front;
rear = a.size - 1;
ordered = a.ordered;
for (int i = a.front; i < a.front + (a.size); i++)
{
circArray[i % capacity] = a.circArray[i % capacity];
}
}
template <class T>
CDA<T>::~CDA()
{
delete[]circArray;
}
template <class T>
T& CDA<T>::operator[](int i)
{
if (i > capacity)
{
cout << "Array index is out of bounds; exiting." << endl;
placeHolder = i;
cout << endl;
return placeHolder;
exit(0);
}
else
{
return circArray[(front + i) % capacity];
}
}
template <class T>
void CDA<T>::AddEnd(T v)
{
size++;
if (front == -1)
{
circArray[0] = v;
front++;
rear++;
return;
}
if (size > capacity)
{
reSize();
}
else if (front == -1)
{
front = 0;
rear = size - 1;
}
else
{
rear = (rear + 1) % capacity;
}
circArray[rear] = v;
}
template <class T>
void CDA<T>::AddFront(T v)
{
size++;
if (size > capacity)
{
reSize();
}
if (front == -1) //means the array is empty
{
front = 0;
rear = capacity % size;
}
else if (front == 0) //means something is in spot 0
{
front = capacity - 1; //puts front at the end and places the input there
}
else //go until it is back at zero
{
front--;
}
circArray[front] = v;
}
template <class T>
void CDA<T>::DelEnd()
{
size--;
if (size <= capacity / 4)
{
Shrink();
}
else if (rear == front)
{
front = -1;
rear = -1;
}
else
{
rear--;
}
}
template <class T>
void CDA<T>::DelFront()
{
size--;
double shrMeasure;
shrMeasure = capacity / 4.0;
if (size <= shrMeasure) // make an empty and shrink function
{
Shrink();
}
/*
else if (front == rear)
{
if (front == 0)
front = size - 1;
else
front++;
}
*/
else
{
if (front == size) //brings it full circle
{
front = 0;
}
else
{
front++;
}
}
if (front > capacity)
front = front % capacity;
}
template <class T>
int CDA<T>::Length()
{
return size;
}
template <class T>
int CDA<T>::Capacity()
{
return capacity;
}
template <class T>
int CDA<T>::Clear()
{
~CDA();
size = 1;
circArray[size] = NULL;
}
template <class T>
bool CDA<T>::Ordered()
{
return ordered;
}
template <class T>
int CDA<T>::SetOrdered()
{
for (int i = 1; i < size - 1; i++)
{
if (circArray[(i - 1)] > circArray[i])
{
ordered = false;
return -1;
}
}
ordered = true;
return 1;
}
template <class T>
T CDA<T>::Select(int k)
{
if (ordered == true)
{
return circArray[(front + k - 1) % capacity];
}
else
QuickSelect(front, front + (size - 1), k);
}
template <class T>
int CDA<T>::QSelPartition(int left, int right)
{
int pivot = circArray[right % capacity];
int x = left - 1;
//Swap(&circArray[pivIndex], &circArray[right]);
for (int i = left; i <= right - 1; i++)
{
if (circArray[i % capacity] <= pivot)
{
x++;
Swap(&circArray[x % capacity], &circArray[i % capacity]);
}
}
Swap(&circArray[(x + 1) % capacity], &circArray[right % capacity]);
return (x + 1);
}
template <class T>
T CDA<T>::QuickSelect(int left, int right, int k)
{
if (k > 0 && k <= (right - left) + 1)
{
int index = QSelPartition(left, right);
if (index - 1 == k - 1)
return circArray[index % capacity];
else if (index - 1 > k - 1)
return QuickSelect(left, index - 1, k);
else
return QuickSelect(index - 1, right, k - index + left - 1);
}
return -1;
}
template <class T>
void CDA<T>::InsertionSort() //must be utilized in quicksort
{
for (int i = front + 1; i < (front + size); i++)
{
int val = circArray[i % capacity];
int inc = (i - 1) % capacity;
while (inc >= 0 && circArray[inc] > val)
{
circArray[(inc + 1) % capacity] = circArray[inc];
inc--;
if (inc == -1)
{
inc = capacity - 1;
}
}
circArray[(inc + 1) % capacity] = val;
}
ordered = true;
}
template <class T>
void CDA<T>::QuickSort() // change to other quicksort before leaving the ferg
{
QuickSort1(front, front + (size - 1));
}
template <class T>
void CDA<T>::QuickSort1(int low, int high)
{
while (low < high)
{
if (high - low < 900)
{
InsertionSort();
break;
}
else
{
int pivot = QSortPartition(low, high);
if (pivot - low < high - pivot)
{
QuickSort1(low, pivot--);
low = pivot + 1;
}
else
{
QuickSort1(pivot++, high);
high = pivot - 1;
}
}
}
}
template <class T>
int CDA<T>::QSortPartition(int low, int high)
{
int pivot = circArray[Median(low, high) % capacity];
Swap(&circArray[(Median(low, high)) % capacity], &circArray[(high) % capacity]);
int index = low % capacity;
for (int i = low; i < high; i++)
{
if (circArray[i % capacity] <= pivot)
{
T t = circArray[i % capacity];
circArray[i % capacity] = circArray[index % capacity];
circArray[index % capacity] = t;
index++;
}
}
Swap(&circArray[index % capacity], &circArray[high % capacity]);
return index;
}
template <class T>
int CDA<T>::Median(int low, int high)
{
T left, mid, right;
left = circArray[low % capacity];
mid = circArray[((low + high) / 2) % capacity];
right = circArray[high % high];
if (left < right && left > mid)
return low % capacity;
if (left < mid && left > right)
return low % capacity;
if (right < left && right > mid)
return high % capacity;
if (right < mid && right > left)
return high % capacity;
if (mid < left && mid > right)
return ((low + high) / 2 % capacity);
if (mid < right && mid > left)
return ((low + high) / 2 % capacity);
}
template <class T>
void CDA<T>::Swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
template <class T>
void CDA<T>::CountingSort(int m) ////NEED TO FIX THIS
{
int* OP = new int[size];
int* Counter = new int[m + 1];
for (int i = front; i <= rear; i++)
{
cout << "CircArray[" << i << "] is " << circArray[i] << endl;
}
for (int i = 0; i <= m; i++)
{
Counter[i] = 0;
}
for (int i = front; i < front + (size); i++)
{
Counter[circArray[i % capacity]]++;
}
for (int i = 1; i <= m; i++)
{
Counter[i] += Counter[i - 1];
}
for (int i = rear - 1; i > 0; i--)
{
OP[Counter[circArray[i]] - 1] = circArray[i];
cout << "Circular array at " << i << " is " << circArray[i] << endl;
Counter[circArray[i]] -= 1;
if (i == front % capacity)
break;
if (i == 0)
i = capacity;
}
for (int i = 0; i < size; i++)
circArray[i] = OP[i];
ordered = true;
front = 0;
}
template <class T>
int CDA<T>::Search(T e)
{
if (ordered == true) //binary search of item e
{
return BinarySearch(front, front + (size - 1), e);
}
else if (ordered == false)
{
for (int i = 0; i < size - 1; i++)
{
if (circArray[i] == e)
return i;
}
}
return -1;
}
template <class T>
int CDA<T>::BinarySearch(int left, int right, T e)
{
while (left <= right)
{
int mid = (left + right) / 2;
int value = circArray[mid % capacity];
if (value == e)
return (mid - front) % capacity;
else if (value < e)
return BinarySearch(mid + 1, right, e);
else if (value > e)
return BinarySearch(left, mid - 1, e);
}
return -1;
}
template <class T>
void CDA<T>::reSize()
{
capacity = capacity * 2;
T *nArray = new T[capacity];
for (int i = 0; i < size - 1; i++)
{
int l = (front + i) % (size-1);
nArray[i] = circArray[l];
}
//delete[]circArray;
circArray = nArray;
front = 0;
rear = (size - 1);
}
template <class T>
void CDA<T>::Shrink()
{
int tFront = front;
capacity = capacity / 2;
T* bArr = new T[capacity];
int index = 0;
while (front <= rear)
{
bArr[index] = circArray[(front + index) % capacity];
index++;
}
T* circArray = bArr;
front = 0;
rear = (size - 1);
}
template <class T>
CDA<T>& CDA<T>::operator=(const CDA<T>& a)
{
if (this != &a)
{
delete[]circArray;
size = a.size;
capacity = a.capacity;
circArray = new T[a.capacity];
front = a.front;
rear = a.size - 1;
ordered = a.ordered;
for (int i = a.front; i < a.front + (a.size); i++)
{
circArray[i % capacity] = a.circArray[i % capacity];
}
}
return *this;
}
template <class T>
int CDA<T>::Front()
{
return front;
}
template <class T>
T CDA<T>::Data(int n)
{
return circArray[n];
}
#include <iostream>
#include "CDA-1.cpp"
using namespace std;
template<class keytype, class valuetype>
class Heap
{
private:
CDA<keytype>* K;
CDA<valuetype>* V;
int size;
public:
Heap()
{
this->K = new CDA<keytype>();
this->V = new CDA<valuetype>();
size = 0;
}
Heap(keytype k[], valuetype v[], int s)
{
//allocate two different arrays for each type
//fill those arrays concurrently using insert
//sort concurrently using heapafy recursively
this->K = new CDA<keytype>(s);
this->V = new CDA<valuetype>(s);
this->size = s;
for (int i = 0; i < s; i++)
{
insert(k[i], v[i]);
}
heapify(s, K->Front());
}
void heapify(int s, int i)
{
//Errors for evans to fix: swap the n's with s.
//Fix the left and right variable logic. Hepaify smallest not small at the bottom.
//Also we need to pass V[] in a parameter so we can edit it in this.
//How to better swap V with K and not just K.
int smallest = i;
int left = 2*i +(-i+1);
int right = 2*i + (-i+2);
keytype kl = K->Data(left);
keytype kr = K->Data(right);
keytype ks = K->Data(smallest);
if (left < s && kl < ks) //FIX
smallest = left;
if (right < s && kr < ks) //FIX
smallest = right;
if (smallest != i)
{
swap(K[i], K[smallest]);
swap(V[i], V[smallest]); //FIX
heapify(s, smallest);
}
}
~Heap() {
return;
}
//items should be inserted using bottom up heap building method
void insert(keytype k, valuetype v)
{
K->AddEnd(k);
V->AddEnd(v);
heapify(size, K->Front());
}
keytype peekKey()
{
int f = K->Front();
return K->Data(f);
}
valuetype peekValue()
{
int f = V->front();
return V->Data(f);
}
keytype extractMin()
{
keytype temp = K->Data(K->Front());
K->DelFront();
V->DelFront();
heapify(size, K->Front());
return temp;
}
void printKey()
{
ActualPrintKey(K->Front());
}
void ActualPrintKey(int n)
{
keytype rt = K->Data(n);
if (rt != size)
{
cout << K->Data(rt) << " ";
ActualPrintKey((2 * n) + (-n + 1));
ActualPrintKey((2 * n) + (-n + 2));
}
}
};
/*
template <class keytype, class valuetype>
class BHeap
{
BHeap();
BHeap(keytype k[], valuetype v[], int s);
~BHeap();
keytype peekKey();
valuetype peekValue();
keytype extractMin();
//items should be inserted using repeated insertion
void insert(keytype k, valuetype v);
void merge(BHeap<keytype, valuetype>& H2);
void printKey();
};
*/
#include <iostream>
#include "Heaps.cpp"
using namespace std;
int main() {
string K[10] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "K" };
int V[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Heap<string, int> T1, T2(K, V, 10);
cout << T2.peekKey() << endl;
cout << endl;
system("pause");
return 0;
}
In general "Access violation reading location", means you are trying to read virtually memory address space to a process which does not belong to your application and the operating system protective mechanism is kicking in to protect the rest of the loaded applications and resource from been accessed (read or write) by your application "memory leak vulnerability". If I was at your place I would review the code and all variables and arrays if they are properly initialized before use. Another thing which needs to be taken in consideration is the operating system and the permissions required by your application (Windows run as Administrator / GNU/Linux sudo).
Cheers

scanf from console and fscanf from file

I got some problems about scanf from console,
I wrote some codes about it and found that it could not read all the input and automatically close after typing first character.
int readLetterGridFromConsole(char letterGrid[MAX_GRID][MAX_GRID]) {
int row, col;
int gridSize;
printf("Enter the size of the letter grid:\n");
scanf("%d", &gridSize);
if(gridSize < 2 || gridSize > MAX_GRID) {
printf("DEBUG: gridSize is %d but not between 2 and %d\n", gridSize, MAX_GRID);
printf("Program terminates.\n");
exit(1);
} else {
printf("Enter the letter grid:\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
scanf(" %c", &letterGrid[row][col]);
}
}
return gridSize;
}
}
I would like to store these input in the 2D array ( letterGrid )
how could I solve this problem? Thanks for help!
But it works for me.
I define a 2-D array char x[MAX_GRID][MAX_GRID]; then pass it to function, then scan input then store them in the x matrix.
Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_GRID 2
int readLetterGridFromConsole(char letterGrid[MAX_GRID][MAX_GRID]) {
int row, col;
int gridSize;
printf("Enter the size of the letter grid:\n");
scanf("%d", &gridSize);
if(gridSize < 2 || gridSize > MAX_GRID) {
printf("DEBUG: gridSize is %d but not between 2 and %d\n", gridSize, MAX_GRID);
printf("Program terminates.\n");
exit(1);
} else {
printf("Enter the letter grid:\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
scanf(" %c", &letterGrid[row][col]);
}
}
//return gridSize;
}
/*
printf("Lettr grid\n\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
printf("%c", letterGrid[row][col]);
}
}
*/
}
int main()
{
char x[MAX_GRID][MAX_GRID];//={{1,2},{3,4}};
readLetterGridFromConsole(x);
printf("after function\n\n\n");
for(int row = 0; row < MAX_GRID; row++) {
for(int col = 0; col < MAX_GRID; col++) {
printf("%c", x[row][col]);
}
}
return 0;
}
Compile and Run
gcc -Wall -Wextra -pedantic-errors code.c -o code
Output
Enter the size of the letter grid:
2
Enter the letter grid:
a
b
c
d
after function
abcd
Consider as array in c pass by reference it can hold values even outside of function readLetterGridFromConsole(x);

Retrieving and manipulating data from file

The following code is supposed to retrieve the data related to the players info, sort it out and then rewrite the file now organized. Going to give an example of the files.
Original layout:
3
2 2
John 33 M 5
Anna 20 F 2
Rody 23 M 1
What it has to look like after the code:
3
2 2
Rody 23 M 1
Anna 20 F 2
John 33 M 5
I made the following code:
vector<string> playerScoresFromFile(const string filename) //Gets each one of those lines with the name, ..., and score of the person
{
int dim = filename[7] - '0'; // char to integer
vector<string> vec;
string line;
ifstream fin (filename.c_str());
for (int i = 0; i < dim + 1; i++)
{
getline(fin, line);
}
while(! fin.eof())
{
getline(fin, line);
vec.push_back(line);
}
return vec;
}
vector< vector<int> > readBoardFromFile(const string filename) //gets the board from the file (first 3 numbers)
{
int dim = filename[7] - '0'; // char to integer
string line;
vector< vector<int> >vec(dim, vector<int>(dim));
ifstream fin (filename.c_str());
int i = 0;
int j, k;
while(i < dim)
{
getline(fin, line);
int sizeOfLine = line.length();
if (line[0] == '\0')
{
break;
}
else
{
for (j = 0, k = 0; j < (sizeOfLine / 3); j++, k += 3)
{
string elementOfVectorStr = (line.substr(k,3));
int elementOfVectorInt = stringToInt(elementOfVectorStr);
if (abs(elementOfVectorInt) > 100) // when the element is a " ", the corresponding integer is always
{ // a very large number, positive or negative
elementOfVectorInt = 0;
}
vec[i][j] = elementOfVectorInt;
}
}
i++;
}
return vec;
}
vector<string> sortPlayersByTime (vector<string> &vec) // Creates a substring of the string extracted by "playerScoresFromFile" and analyses the times (Which are the last numbers to the right)
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
swap(vec[i], vec[i+1]);
}
}
return vec;
}
bool isOrdered (const vector<string> vec) //Checks if the vector is ordered
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
return false;
}
}
return true;
}
void writeBoardToFile(vector< vector<int> >&vec, string filename) //Rewrites the board to the file (Those first 3 numbers of the file)
{
ofstream fout(filename.c_str());
for (size_t i = 0; i < vec.size(); i++)
{
for (size_t j = 0; j < vec.size(); j++)
{
if(vec[i][j] != 0)
{
fout << setw(3) << vec[i][j];
}
else
{
fout << setw(3) << " ";
}
}
fout << endl;
}
fout << endl;
}
void vec_to_file(vector<string> vec, string filename) //Rewrites the vector to the file
{
ofstream fout(filename, ios::app);
for (int i = 0; i < vec.size(); i++)
{
fout << vec[i] <<endl;
}
}
void displayFile (string filename) //Displays the final board to check if it worked
{
vector<string> vec;
string line;
ifstream myfile (filename);
while ( ! myfile.eof() )
{
getline (myfile, line);
vec.push_back(line);
}
for (size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] <<endl;
}
}
int main()
{
vector< vector<int> > vec = readBoardFromFile("puzzle_2x2_001.txt");
vector<string> vecxz = playerScoresFromFile("puzzle_2x2_001.txt");
writeBoardToFile(vec, "puzzle_2x2_001.txt"); //Writes the board to the file
while (! isOrdered(vecxz)) //This loop should run while they haven't been sorted out, but the program crashes here and I have no idea why.
{
sortPlayersByTime(vecxz);
}
//vec_to_file(vecxy, "puzzle_2x2_001.txt"); //Should write the vector to the file upon sorting them out successfully.
cin.get();
}
My problem is the program crashes everytime it gets to the while(! isOrdered(vecxz)) loop but I have no idea why. Can anyone give me a hand? I'd be thankful :)

Read/write on a pen drive using libusb: libusb_bulk_transfer()

I am trying to perform read and write operations on a pen drive.
Details: Vendor ID: 8564 and Product ID: 1000. It is a Transcend JetFlash mass storage device.
I am keen to know that whether it is possible to achieve a read/write on a pen drive. If it is, then is it going to happen the way I have tried in the code provided below.
I have learnt the methods to get the device id, product id and endpoint addresses. This is what I have implemented.
Here the device is getting acknowledged and opened. And, even the interface claims it is successful.
But bulk transfer functions return -1.
What is the explanation?
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include </usr/include/libusb-1.0/libusb.h>
#define BULK_EP_OUT 0x82
#define BULK_EP_IN 0x02
int main(void)
{
int r = 0, e = 0;
struct libusb_device_handle *handle = NULL;
struct libusb_device **devs;
struct libusb_device *dev;
struct libusb_device_descriptor desc;
char str1[256], str2[256];
/* Init libusb */
r = libusb_init(NULL);
if (r < 0)
{
printf("\nfailed to initialise libusb\n");
return 1;
}
handle = libusb_open_device_with_vid_pid(NULL, 0x8564, 0x1000);
if(handle == NULL)
{
printf("\nError in device opening!");
}
else
printf("\nDevice Opened");
// Tell libusb to use the CONFIGNUM configuration of the device
libusb_set_configuration(handle, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
}
e = libusb_claim_interface(handle, 0);
if(e < 0)
{
printf("\nCannot Claim Interface");
}
else
printf("\nClaimed Interface");
/* Communicate */
int bytes_read;
int nbytes = 256;
unsigned char *my_string, *my_string1;
int transferred = 0;
my_string = (unsigned char *) malloc (nbytes + 1);
my_string1 = (unsigned char *) malloc (nbytes + 1);
strcpy(my_string, "divesd");
printf("\nTo be sent : %s", my_string);
e = libusb_bulk_transfer(handle, BULK_EP_OUT, my_string, bytes_read, &transferred, 5000);
printf("\nXfer returned with %d", e);
printf("\nSent %d bytes with string: %s\n", transferred, my_string);
libusb_bulk_transfer(handle, BULK_EP_IN, my_string1, 256, &transferred, 5000);
printf("\nXfer returned with %d", e); //It returns -1... This is an error, I guess.
printf("\nReceived %d bytes with string: %s\n", transferred, my_string1);
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
return 0;
}
Try the code given below and it should work on LPC2148. I have tested this with an LPC2148 configured to receive an interrupt from USB after a write happens (from user-space) and the RTC starts running.
Answering to your question whether it involves a kernel driver in read/write or not: As far as I have studied, you have to detach the kernel driver and claim the interface using libusb APIs. Though I am not sure whether it can be done without detaching it or not.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include </usr/local/include/libusb-1.0/libusb.h>
#define BULK_EP_OUT 0x82
#define BULK_EP_IN 0x08
int interface_ref = 0;
int alt_interface, interface_number;
int print_configuration(struct libusb_device_handle *hDevice, struct libusb_config_descriptor *config)
{
char *data;
int index;
data = (char *)malloc(512);
memset(data, 0, 512);
index = config->iConfiguration;
libusb_get_string_descriptor_ascii(hDevice, index, data, 512);
printf("\nInterface Descriptors: ");
printf("\n\tNumber of Interfaces: %d", config->bNumInterfaces);
printf("\n\tLength: %d", config->bLength);
printf("\n\tDesc_Type: %d", config->bDescriptorType);
printf("\n\tConfig_index: %d", config->iConfiguration);
printf("\n\tTotal length: %lu", config->wTotalLength);
printf("\n\tConfiguration Value: %d", config->bConfigurationValue);
printf("\n\tConfiguration Attributes: %d", config->bmAttributes);
printf("\n\tMaxPower(mA): %d\n", config->MaxPower);
free(data);
data = NULL;
return 0;
}
struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev, struct libusb_device_handle *handle)
{
struct libusb_device_handle *hDevice_req;
struct libusb_config_descriptor *config;
struct libusb_endpoint_descriptor *endpoint;
int altsetting_index, interface_index=0, ret_active;
int i, ret_print;
hDevice_req = handle;
ret_active = libusb_get_active_config_descriptor(dev, &config);
ret_print = print_configuration(hDevice_req, config);
for (interface_index=0;interface_index<config->bNumInterfaces;interface_index++)
{
const struct libusb_interface *iface = &config->interface[interface_index];
for (altsetting_index=0; altsetting_index<iface->num_altsetting; altsetting_index++)
{
const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];
int endpoint_index;
for(endpoint_index=0; endpoint_index<altsetting->bNumEndpoints; endpoint_index++)
{
const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];
endpoint = ep;
alt_interface = altsetting->bAlternateSetting;
interface_number = altsetting->bInterfaceNumber;
}
printf("\nEndPoint Descriptors: ");
printf("\n\tSize of EndPoint Descriptor: %d", endpoint->bLength);
printf("\n\tType of Descriptor: %d", endpoint->bDescriptorType);
printf("\n\tEndpoint Address: 0x0%x", endpoint->bEndpointAddress);
printf("\n\tMaximum Packet Size: %x", endpoint->wMaxPacketSize);
printf("\n\tAttributes applied to Endpoint: %d", endpoint->bmAttributes);
printf("\n\tInterval for Polling for data Tranfer: %d\n", endpoint->bInterval);
}
}
libusb_free_config_descriptor(NULL);
return endpoint;
}
int main(void)
{
int r = 1;
struct libusb_device **devs;
struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;
struct libusb_device *dev, *dev_expected;
struct libusb_device_descriptor desc;
struct libusb_endpoint_descriptor *epdesc;
struct libusb_interface_descriptor *intdesc;
ssize_t cnt;
int e = 0, config2;
int i = 0, index;
char str1[64], str2[64];
char found = 0;
// Init libusb
r = libusb_init(NULL);
if(r < 0)
{
printf("\nFailed to initialise libusb\n");
return 1;
}
else
printf("\nInit successful!\n");
// Get a list of USB devices
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0)
{
printf("\nThere are no USB devices on the bus\n");
return -1;
}
printf("\nDevice count: %d\n-------------------------------\n", cnt);
while ((dev = devs[i++]) != NULL)
{
r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
{
printf("Failed to get device descriptor\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
e = libusb_open(dev, &handle);
if (e < 0)
{
printf("Error opening device\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nDevice Descriptors: ");
printf("\n\tVendor ID: %x", desc.idVendor);
printf("\n\tProduct ID: %x", desc.idProduct);
printf("\n\tSerial Number: %x", desc.iSerialNumber);
printf("\n\tSize of Device Descriptor: %d", desc.bLength);
printf("\n\tType of Descriptor: %d", desc.bDescriptorType);
printf("\n\tUSB Specification Release Number: %d", desc.bcdUSB);
printf("\n\tDevice Release Number: %d", desc.bcdDevice);
printf("\n\tDevice Class: %d", desc.bDeviceClass);
printf("\n\tDevice Sub-Class: %d", desc.bDeviceSubClass);
printf("\n\tDevice Protocol: %d", desc.bDeviceProtocol);
printf("\n\tMax. Packet Size: %d", desc.bMaxPacketSize0);
printf("\n\tNumber of Configurations: %d\n", desc.bNumConfigurations);
e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));
if (e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nManufactured: %s", str1);
e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));
if(e < 0)
{
libusb_free_device_list(devs, 1);
libusb_close(handle);
break;
}
printf("\nProduct: %s", str2);
printf("\n----------------------------------------");
if(desc.idVendor == 0xffff && desc.idProduct == 0x4)
{
found = 1;
break;
}
}//end of while
if(found == 0)
{
printf("\nDevice NOT found\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return 1;
}
else
{
printf("\nDevice found");
dev_expected = dev;
hDevice_expected = handle;
}
e = libusb_get_configuration(handle, &config2);
if(e!=0)
{
printf("\n***Error in libusb_get_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
printf("\nConfigured value: %d", config2);
if(config2 != 1)
{
libusb_set_configuration(handle, 1);
if(e!=0)
{
printf("Error in libusb_set_configuration\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nDevice is in configured state!");
}
libusb_free_device_list(devs, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
else
{
printf("\nCouldn't detach kernel driver!\n");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
}
e = libusb_claim_interface(handle, 0);
if(e < 0)
{
printf("\nCannot Claim Interface");
libusb_free_device_list(devs, 1);
libusb_close(handle);
return -1;
}
else
printf("\nClaimed Interface\n");
active_config(dev_expected, hDevice_expected);
// Communicate
char *my_string, *my_string1;
int transferred = 0;
int received = 0;
int length = 0;
my_string = (char *)malloc(nbytes + 1);
my_string1 = (char *)malloc(nbytes + 1);
memset(my_string, '\0', 64);
memset(my_string1, '\0', 64);
strcpy(my_string, "Prasad Divesd");
length = strlen(my_string);
printf("\nTo be sent: %s", my_string);
e = libusb_bulk_transfer(handle, BULK_EP_IN, my_string, length, &transferred, 0);
if(e == 0 && transferred == length)
{
printf("\nWrite successful!");
printf("\nSent %d bytes with string: %s\n", transferred, my_string);
}
else
printf("\nError in write! e = %d and transferred = %d\n", e, transferred);
sleep(3);
i = 0;
for(i = 0; i < length; i++)
{
e = libusb_bulk_transfer(handle, BULK_EP_OUT, my_string1, 64, &received, 0); //64: Max Packet Length
if(e == 0)
{
printf("\nReceived: ");
printf("%c", my_string1[i]); //Will read a string from LPC2148
sleep(1);
}
else
{
printf("\nError in read! e = %d and received = %d\n", e, received);
return -1;
}
}
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
printf("\n");
return 0;
}

Factorial in bignum library

Ive tried to create my own implementation of a bignum library
I cant seem to get the factorial to work. If I ask it to solve 4!, it gives out 96. It multiplies 4 twice. similarly, 5! is 600, not 120. I haven't implemented division, so I cant/dont want to divide the answer by the number
//bignum project
#include <iostream>
using namespace std;
class bignum
{
public:
int number[100];
int dpos;
int operator/ (bignum);
bignum operator- (bignum);
bignum operator* (bignum);
bignum operator+ (bignum);
bignum operator= (string);
void output()
{
int begin=0;
for(int i=0; i<=99; i++)
{
if(number[i]!=0 || begin==1)
{
cout<<number[i];
begin=1;
}
}
}
};
bool num_is_zero(bignum k)
{
for(int a=0; a<=99; a++)
{
if(k.number[a]!=0)
{
return false;
}
}
return true;
}
bignum factorial(bignum a)
{
bignum j;
bignum fact;
fact="1";
while(!num_is_zero(a))
{
j="1";
fact=fact*a;
a=a-j;
}
return fact;
}
bignum bignum::operator= (string k)
{
int l;
l=k.length()-1;
for(int h=0; h<=99; h++)
{
number[h]=0;
}
for(int a=99; a>=0 && l>=0; a--)
{
number[a]=k[l]-'0';
l--;
}
}
bignum bignum::operator+ (bignum b)
{
bignum a;
int carry=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
a.number[i]= number[i]+b.number[i]+a.number[i];
if(a.number[i]>9)
{
carry=(a.number[i]/10);
a.number[i-1]+=carry;
a.number[i]=(a.number[i]%10);
}
}
return (a);
}
bignum bignum::operator- (bignum c)
{
bignum a;
int sign=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
if(number[i]<c.number[i])
{
number[i]+=10;
if(i!=0)
number[i-1]--;
}
a.number[i]=number[i]-c.number[i];
}
return (a);
}
bignum bignum::operator* (bignum b)
{
bignum ans;
int ans_grid[100][100],x,lines=0,carry,sum[100];
for(int a=0; a<=99; a++)
{
for(int b=0; b<=99; b++)
{
ans_grid[a][b]=0;
}
}
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
I think your problem is that sum is uninitialized in your operator*. I'm reluctant to give a partial answer, since I took the code and fiddled with it a bit, so here's my version which appears to work (and also prints "0" correctly):
Update: I couldn't resist making several structural improvements. I didn't touch your multiplication routine, so you should still be able to extract the bugfix even if you don't care for the rest.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class bignum
{
public:
int number[100];
bignum() { std::fill(number, number + 100, 0); }
bignum(const bignum & other) { std::copy(other.number, other.number + 100, number); }
bignum(const std::string &);
bignum & operator-=(const bignum &);
inline bignum operator-(const bignum & c) const { return bignum(*this) -= c; }
bignum operator*(const bignum &) const;
inline bignum & operator= (const std::string & k) { return *this = bignum(k); }
inline operator bool() const
{
for (size_t a = 0; a < 100; ++a)
if (number[a] != 0) return true;
return false;
}
};
std::ostream & operator<<(std::ostream & o, const bignum & b)
{
bool begun = false;
for (size_t i = 0; i < 100; ++i)
{
if (begun || b.number[i] != 0)
{
cout << b.number[i];
begun = true;
}
}
if (!begun) o << "0";
return o;
}
bignum::bignum(const std::string & k)
{
std::fill(number, number + 100, 0);
for(size_t h = 0; h < std::min(k.length(), 100U); ++h)
number[99 - h] = k[k.length() - 1 - h] - '0';
}
bignum & bignum::operator-=(const bignum & c)
{
for (int i = 99; i >= 0; --i)
{
if (number[i] < c.number[i])
{
number[i] += 10;
if (i != 0) --number[i-1];
}
number[i] -= c.number[i];
}
return *this;
}
bignum bignum::operator*(const bignum & b) const
{
bignum ans;
int ans_grid[100][100], lines = 0, carry, sum[100];
std::fill(sum, sum + 100, 0);
for (size_t i = 0; i < 100; ++i) std::fill(ans_grid[i], ans_grid[i] + 100, 0);
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
bignum factorial(bignum a)
{
bignum j; j = "1";
bignum fact; fact="1";
while(a)
{
fact = fact * a;
a = a-j;
}
return fact;
}
int main(int argc, char * argv[])
{
if (argc < 2) return 0;
bignum a;
a = std::string(argv[1]);
bignum b = factorial(a);
cout << a << std::endl << b << std::endl;
}
The string assignment is still broken for strings with more than one digit, but that wasn't your question I suppose...