Reputation: 19
I am trying to create a function that capitalises all chars in an array.
#include <stdio.h>
#include <string.h>
void capitaliser(char inputText[])
{
int counter;
char upperLetter;
char lowerLetter;
for (counter = 0; counter < 26; counter++)
{
lowerLetter = 'a';
for (char upperLetter = 'A'; upperLetter <= 'Z'; upperLetter++)
{
if(inputText[counter] == lowerLetter)
inputText[counter] = upperLetter;
lowerLetter++;
}
}
}
int main( void )
{
int counter;
char array1[26]; = {'\0'};
char array2[26]; = {'\0'};
scanf("%s %s", array1, array2);
capitaliser(array1[26]);
capitaliser(array2[26]);
for ( counter = 0; counter < 26; counter++ )
{
printf("\n%c %c", array1[counter], array2[counter]);
}
}
When the code from the function is placed in main and 'inputText' is replaced with either 'array1' or 'array2' the program runs fine and gives the desired outputs. However, when I try to run the code as a function I am greeted by 'Fatal Runtime Error'.
From this I assume that I am setting up the function incorrectly. Am I missing something incredibly obvious?
Upvotes: 1
Views: 146
Reputation: 1575
you are referring to a location which is you are not supposed to.
array1[26]
actually does not exists. int array1[length]
is an array of size length whose index starts from 0
and end with length-1
.
The way you are passing the array is inappropriate, this way you will be sending only one value to the function and the function definition is bound to receive an array, this also leads to an error.
The better way to send an array is <functionName>(array1)
, where array1 being my array variable.
Upvotes: 0
Reputation: 409356
In the expression
capitaliser(array1[26])
array[26]
passes the twenty-seventh element of the array array1
to the function, converted to a pointer. First of all, your index is out of bounds of the array, secondly passing a single character converted to a pointer will not pass a valid pointer.
You want e.g.
capitaliser(array1)
Note the lack of indexing.
Upvotes: 2