I am not sure why wont this work.I am trying to print lines(from input) that are longer than 80 characters.But i dont get correct characters at all.I am not sure what am i doing wrong.Anyone there knows ??
Note: I dont want you to write me the whole new program doing this function (printing lines that are longer than 80).I just wanna know the wrong side of my program.Correction
Note:Last line overwrites the previous ones.
#include <stdio.h>
#define MAXARRAYSIZE 500
char c;
int i = 0;
int j = 0;
int jCopy = 0;
char line[MAXARRAYSIZE];
char linesToPrint[MAXARRAYSIZE][MAXARRAYSIZE];
void emptyArray(char theArray[]);
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char from[], int toIndex, int lengthSoFar);
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX);
int main(void) {
while ((c = getchar()) != EOF) {
if (i > MAXARRAYSIZE) {
i = 0;
}
if (j > MAXARRAYSIZE) {
j = 0;
}
if (c != '\n') {
line[i] = c;
i++;
//printf("%d",i);
} else {
printf("\n j:%d \n i:%d", j, i);
j++;
jCopy = j;
if (i >= 10) {
InsertArrayIntoArray(linesToPrint, line, j, i);
//printArray(linesToPrint, j, i);
}
emptyArray(line);
i = 0;
}
}
printArray(linesToPrint, jCopy);
}
void emptyArray(char theArray[]) {
int i;
for (i = 0; i < sizeof(theArray) / sizeof(theArray[0]); i++) {
theArray[i] = 0;
}
}
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d",toSize,whichSize);
for (i = 0; i < toSize; i++) {
for (j = 0; j < whichSize; j++) {
to[i][j] = which[j];
}
}
}
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX) {
int i, j;
for (i = 0; i < lengthSoFarX; i++) {
printf("\n Line %d :", i + 1);
printf(" %s\n", theArray[i]);
}
}
First of all the sizeof(theArray) cannot be taken because theArray is pointer as Joachim Pileborg pointed out.And the second mistake is in InsertArrayIntoArray function.
It should be like this :
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d", toSize, whichSize);
for (j = 0; j < whichSize; j++) {
to[toSize][j] = which[j];
}
}
Related
I have a file with say 4 sentences, I know that there are 4 because each sentence has '.' at the end.
What I did was read from the file given and paste each sentence in a 2 dimensional array like so:
char sentence[0][200] = "Hello how are you."
char sentence [1][200] = "I'm good thanks. etc.
Here is the code for this:
int main()
{
char sentence[RSIZ][LSIZ];
char fname[20] = "t.txt";
FILE *fptr = NULL;
int i = 0;
int tot = 0;
char c;
int nrsentences = 0;
printf("\n\n Read the file and store the lines into an array :\n");
printf("------------------------------------------------------\n");
fptr = fopen(fname, "r");
// Check if file exists
if (fptr == NULL)
{
printf("Cant open the file %s", fname);
return 0;
}
// Sentences counter from file
for (c = getc(fptr); c != EOF; c = getc(fptr))
if (c == '.') // Increases if found '.'
nrsentences = nrsentences + 1;
fptr = fopen(fname, "r");
for (i=0; i<nrsentences; i++)
fgets(sentence[i], 200, fptr);
Then I would separate the this array in to words with this code:
(still in main(){})
char newString[10][30];
int j,ctr;
j=0; ctr=0;
for (int k = 0; k < nrsentences; k++) {
for(i=0;i<=(strlen(frases[k]));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(sentence[k][i]==' '|| sentence[k][i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=sentence[k][i];
j++;
}
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s ",newString[i]);
Then here is the problem (I think), the part of the scrambling code.
This works like this:
I give the code: the sentences and the inedex.
by default it is like this
index-> 0 1 2 3
sentence-> Hello how are you
but with this code it converts to this:
index-> 3 2 0 1
sentence-> you are Hello how
int index[] = {2,3,5,1,0,4,7,6}; //here I have a function that generates the random list(which I dont know yet how to make it work here
int n = nrsentences;
randomize(newString, index, n, nrsentences);
printf("Reordered array is: \n");
for (int i=0; i<n; i++)
printf ("%s ", newString[i]);
return 0;
}
Here is the randomize() function
void randomize(char* arr[], int index[], int n, int nrsentences)
{
printf("%d", n);
char* temp[n];
// arr[i] should be present at index[i] index
//for (int k = 0; k < nrsentences; k++){
for (int i=0; i<n; i++)
temp[index[i]] = arr[i];
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
{
arr[i] = temp[i];
index[i] = i;
}
//}
}
And here is the index randomizer, which I dont know yet (didnt try) how to add it to the main, or randomize function.
int *random_number(int words)
{
int array[25];
int x, p, count;
int i=0;
srand(time(NULL));
while(i< words){
int r=rand()% words +1;
for (x = 0; x < i; x++)
{
if(array[x]==r){
break;
}
}
if(x==i){
array[i++]=r;
}
}
for(p=0;p<words;p++){
printf("%d ", array[p]);
}
return array;
}
or
int array[25];
int words = 5;
int x, p, count;
int i=0;
srand(time(NULL));
while(i< words){
int r=rand()% words +1;
for (x = 0; x < i; x++)
{
if(array[x]==r){
break;
}
}
if(x==i){
array[i++]=r;
}
}
for(p=0;p<words;p++){
printf("%d ", array[p]);
I have this simple program which has to receive in input a matrix[d][d] with every element separated by a , whenever is given the input AddM, then it is supposed to print the matrix.
It works well when the d is small, let's say around 20, but if I enter a larger d then it gives me a segmentation fault (core dump) error.
Can somebody explain why it has this behaviour?
Thank you for your time and sorry if my question is stupid.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGHT 5
int menu(char c[]);
int **buildAdjMat(int **m);
int d;
int main() {
char *command;
int m_result = 1;
int i = 0, j = 0;
int **m;
if (scanf("%d", &d) == 0)
return 0;
printf("d: %d\n", d);
m = (int **)malloc(d * sizeof(int *));
for (i = 0; i < d; i++) {
m[i] = (int *)malloc(d * sizeof(int));
}
do {
command = (char*)malloc(sizeof(char) * MAX_LENGHT);
if (scanf("%s", command) == 0)
return 0;
m_result = menu(command);
if (m_result == 1) {
m = buildAdjMat(m);
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
free(command);
} else {
printf("End! with value %d", m_result);
free(command);
}
} while(m_result == 1);
free(m);
return 0;
}
int menu(char c[]) {
if (strcmp(c, "AddM") == 0) {
printf("AddM!\n");
return 1;
} else {
return -1;
}
}
int **buildAdjMat(int **m) {
int i = 0, j = 0;
char c = '\0';
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
if (scanf("%d", &m[i][j]) == 0)
return NULL;
if (scanf("%c", &c) == 0)
return NULL;
}
}
return m;
}
I am trying to create a program to solve a wordsearch from a 2D array using only pointers. In my primary function for doing the actual search for the words I have a while loop that is supposed to keep going as long as i doesn't exceed the length of the word and as long as the letters from the word correspond to the letters on the grid. After finding the word it should make the letters on the grid lowercase and print out that it found the word. Here is my entire program right now.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void printPuzzle(char** arr, int n);
void searchPuzzle(char** arr, int n, char** list, int listSize);
void searchWord(int j, int k, int gridsize, char** arr, char** list, int listPos);
int main(int argc, char **argv) {
int bSize = 15;
if (argc != 2) {
fprintf(stderr, "Usage: %s <puzzle file name>\n", argv[0]);
return 2;
}
int i, j;
FILE *fptr;
char **block = (char**)malloc(bSize * sizeof(char*));
char **words = (char**)malloc(50 * sizeof(char*));
fptr = fopen(argv[1], "r");
if (fptr == NULL) {
printf("Cannot Open Puzzle File!\n");
return 0;
}
for(i=0; i<bSize; i++){
*(block+i) = (char*)malloc(bSize * sizeof(char));
fscanf(fptr, "%c %c %c %c %c %c %c %c %c %c %c %c %c %c %c\n", *(block+i), *(block+i)+1, *(block+i)+2, *(block+i)+3, *(block+i)+4, *(block+i)+5, *(block+i)+6, *(block+i)+7, *(block+i)+8, *(block+i)+9, *(block+i)+10, *(block+i)+11, *(block+i)+12, *(block+i)+13, *(block+i)+14 );
}
fclose(fptr);
fptr = fopen("states.txt", "r");
if (fptr == NULL) {
printf("Cannot Open Words File!\n");
return 0;
}
for(i=0; i<50; i++){
*(words+i) = (char*)malloc(20 * sizeof(char));
fgets(*(words+i), 20, fptr);
}
for(i=0; i<49; i++){
*(*(words+i) + strlen(*(words+i))-2) = '\0';
}
printf("Printing list of words:\n");
for(i=0; i<50; i++){
printf("%s\n", *(words + i));
}
printf("\n");
printf("Printing puzzle before search:\n");
printPuzzle(block, bSize);
printf("\n");
searchPuzzle(block, bSize, words, 50);
printf("\n");
printf("Printing puzzle after search:\n");
printPuzzle(block, bSize);
printf("\n");
return 0;
}
void printPuzzle(char** arr, int n){
for(int i = 0; i < n; i++){
printf("\n");
for(int j = 0; j < 15; j++){
printf("%c ", *(*(arr+i)+j));
}
}
}
void searchPuzzle(char** arr, int n, char** list, int listSize){
for(int i = 0; i < listSize; i++){
for(int j = 0; j < 15; j++){
for(int k = 0; k < 15; k++){
searchWord(j, k, 15, arr, list, i);
}
}
}
}
void searchWord(int j, int k, int gridsize, char** arr, char** list, int listPos){
int wordlength = strlen(*(list+listPos));
if(j+wordlength <= gridsize){ //Horizontal
int i = 0;
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+k) = tolower(*(*(arr+(j+i))+k));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++)
printf("%c", *(*(list+listPos)+i));
}
}
if(k+wordlength <= gridsize){ //Vertical
int i = 0;
while(i < wordlength && *(*(arr+j)+(k+i)) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+j)+(k+i)) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+k) = tolower(*(*(arr+(j+i))+k));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++){
printf("%c", *(*(list+listPos)+i));
}
}
}
if(j+wordlength <= gridsize && k+wordlength <= gridsize){ //Diagonal
int i = 0;
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
if(i == wordlength){
while(i > 0 && *(*(arr+(j+i))+(k+i)) == *(*(list+listPos)+i)){
*(*(arr+(j+i))+(k+i)) = tolower(*(*(arr+(j+i))+(k+i)));
i--;
}
printf("Word found: ");
for(i = 0; i < wordlength; i++)
printf("%c", *(*(list+listPos)+i));
}
}
}
This is the part I believe there is a problem with.
while(i < wordlength && *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
If I print out the decimal value of i after this while loop it should at some point approach the length of one of the words as I know some words are horizontal, however every time it loops through and prints the value of i it never exceeds 1 which means the while loop never runs more than once which is impossible with the wordsearch files I am using to test this. What is causing this to happen? It is also 0 or 1 for every other direction when I try, the example above was just the while loop from the horizontal search.
There may also be a problem with the function searchPuzzle and the amount it loops through. However, I think that may be just my imagination.
Additional Info: The grid is 15x15 and there are 50 words in the list.
I think that you might need to declare Wordsearch again after the && -
while(i < wordlength && wordlength *(*(arr+(j+i))+k) == *(*(list+listPos)+i)){
i++;
}
I am trying to return a char** from a function to main so I can do stuff with it, but when I print it out it gives me random characters. I'm at a loss.
main VV
// ./main < data/filelist.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hist.h"
int main(){
int count = 0;
int i;
char** files = read(&count);
displayList(files, count);
char** array = splitFiles(files, count);
printf("IN MAIN: array[0] - %s\n", array[0]);
Histogram* p;
printf("here\n");
int histArrayCount = calcHistogram(&array[0], &count, &p);
printf("here\n");
displayHistogram(p, histArrayCount);
printf("here\n");
}
hist.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hist.h"
int calcHistogram (char** a, int* count, Histogram** q) {
int i, k;
int j = 0;
int histArrayCount = 0;
Histogram* p = (Histogram*)malloc((*count) * sizeof(Histogram));
for (k = 0; k < *count; k++) {
p[k].num = "1";
p[k].freq = 0;
}
for (i = 0; i <= *count; i++) {
while ((strcmp(p[j].num, "1") != 0) && (strcmp(p[j].num, a[i]) != 0)) {
j++;
}
if (strcmp(p[j].num, "1") == 0) {
p[j].num = a[i];
p[j].freq = 1;
histArrayCount++;
}
else if ((strcmp(p[j].num, a[i]) == 0)) {
p[j].freq += 1;
}
else {
printf("ERROR\n");
}
j = 0;
}
*q = p;
return histArrayCount;
}
void displayHistogram (Histogram* p, int histArrayCount) {
int i;
for (i = 0; i < histArrayCount - 1; i++) {
printf("value %s: freq %d\n", p[i].num, p[i].freq);
}
printf("\n");
}
char** splitFiles(char** files, int count) {
int i;
char** array = (char**)malloc((count)*sizeof(char*));
FILE* fp;
int c = 0;
for(i = 0; i < count; i++) {
char buff[255];
fp = fopen(files[i], "r");
array[i] = fgets(buff, 255, (FILE*)fp);
printf("%d : %s\n", i, buff);
}
printf("array[0] = %s\n", array[0]);
return array;
}
void displayList(char** a, int c) {
int i;
for (i = 0; i < c; i++) {
printf("File %d: %s\n", i, a[i]);
}
printf("\n");
}
char** read(int* c){
int count = 0;
int i;
char** a = (char**)malloc(100*sizeof(char*));
for (i = 0; i< 100; i++) {
a[count] = (char*)malloc(100*sizeof(char));
count++;
}
count = 0;
int endOfFile = scanf("%s", a[count]);
while (endOfFile != EOF) {
count++;
endOfFile = scanf("%s", a[count]);
}
*c = count;
return a;
}
When I print the array at index 0 in here it gives me what is actually there, but when I do the same thing in main it does not. It gives me three random characters.
hist.h
typedef struct Histogram {
char* num;
int freq;
} Histogram;
char** read(int* c);
void displayList(char** a, int c);
int calcHistogram (char** a, int* c, Histogram** p);
void displayHistogram (Histogram* a, int histArrayCount);
char** splitFiles (char** files, int count);
My program is fairly simple.
Read the H,W, horizontal char, vertical char from a user.
And then print out the square by the given params.
However, when user type 'y' to run the second time.
the height param is always missing.
I didn't get it.
A likely buggy point i can think is that the input buffer might not clean.
Any idea?
C program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
const int USER_INPUT_SIZE_EACH_LINE = 999;
void draw_middle_lines(char *middle_line, int width) {
printf("%s", middle_line);
for (int i = 2; i < width; i++) {
printf(" ");
}
printf("%s\n", middle_line);
}
void draw_bound_line(char *bound_char, int width) {
for (int i = 0; i < width; i++) {
printf("%s", bound_char);
}
printf("\n");
}
void clearNewline(char *line, int max_len) {
for (int i = 0; i < max_len; i++){
printf("%c", line[i]);
}
printf("\n");
for (int i = 0; i < max_len; i++) {
if (line[i] == '\n') {
line[i] = '\0';
}
}
}
char **ask_user_preference() {
printf("\nask user preference\n");
const int NUM_OF_PROMPTS = 4;
const char *prompt[] = {
"please input height:",
"please input width:",
"please input horizontal char:",
"please input vertical char:",
};
char **preference;
preference = malloc(NUM_OF_PROMPTS);
for (int i = 0; i < NUM_OF_PROMPTS; i++) {
preference[i] = malloc(USER_INPUT_SIZE_EACH_LINE);
memset(preference[i], 0, sizeof(char) * USER_INPUT_SIZE_EACH_LINE);
printf("%s", prompt[i]);
fgets(preference[i], USER_INPUT_SIZE_EACH_LINE, stdin);
clearNewline(preference[i], USER_INPUT_SIZE_EACH_LINE);
}
return preference;
}
void draw(int w, int h, char *bound_char, char *middle_char) {
printf("width: %d\n", w);
printf("height: %d\n", h);
draw_bound_line(bound_char, w);
for (int i = 2; i < h; i++) {
draw_middle_lines(middle_char, w);
}
draw_bound_line(bound_char, w);
}
void clr_input_buffer() {
for (;;) {
int c = getchar();
if (c == EOF || c == '\n')
break;
}
}
int main() {
char *cont = malloc(10+1);
do {
char **pref = ask_user_preference();
int height = atoi(pref[0]);
int width = atoi(pref[1]);
char *bound_char = pref[2];
char *middle_char = pref[3];
draw(width, height, bound_char, middle_char);
printf("continue to play (y/n)? ");
fgets(cont, 2, stdin);
if (strncmp(cont, "y", 1) == 0) {
clr_input_buffer();
}else{
break;
}
} while (1);
printf("BYE BYE~");
return 0;
}