I have a program in which a user inputs how many sentences they want, and then then be prompted to input the sentences. they cannot enter more than ten sentences. when i test, if i enter more than 5, i get a bus error code. here is my code, i am calling two functions in .h files that i dont believe are relevant but i will provide them anyways.
//this program will take in user input for a number of sentences up to ten, each with 100 char or less, and convert them all to uppercase
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "convert.h"
int main () {
int i; //increment
int numberofsentences; //number of sentences
char **sentence_array; // sentence array
sentence_array = (char **)malloc(numberofsentences*sizeof(char));
printf ("I will take up to ten sentences of up to 100 chars each, and convert them to uppercase, as well as give you stats on them.
");
printf ("How many sentences would you like?
");
scanf ("%d", &numberofsentences);
fgetc(stdin);
//user inputs the sentences based on the number that was provided
for (i = 0; i< numberofsentences; i++) {
sentence_array[i] = (char *)malloc(100 * sizeof(char));
printf ("Enter sentence :");
fgets(sentence_array[i], 101, stdin);
printf ("
");
}
//call function that converts all arrays to uppercase
convertAll(sentence_array, numberofsentences);
printf("Your converted sentences are:
");
//print out every sentence thats converted to uppercase
for (i = 0; i < numberofsentences; i++){
//convertSentence(sentence_array[i]);
printf("%s", sentence_array[i]);
}
}
and functions.c file
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "convert.h"
//function to convert char array to uppercase
void convertSentence(char *sentence){
int i;
for (i = 0; i <strlen(sentence); i++){
sentence[i] = toupper(sentence[i]);
}
}
//function to convert array of all sentences and converts all to upper
void convertAll(char **sentenceList, int numOfSentences){
int i;
for (i = 0; i < numOfSentences; i++){
convertSentence(sentenceList[i]);
}
}
i feel like its something to do with the memory allocation.
and as a note: i know that scanf and fgets are terrible, but my professor told us to use them so ... thanks for helping
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…