This is a program I wrote (not including "string.h") which is meant to convert a string to upper case. It works with a single string - so far so good.
I run into trouble when I try to create an array of strings so I can test various strings in turn as part of a loop.
So, I don't understand why the program works when my string is declared as char test_string[] = "TEST";
but it does not work when I declare an array of pointers to strings.
This is the working single string version (followed by the non-working array of strings version):
#include <stdio.h>
void toAlpha(char*);
int str_len(char*);
int main()
{
char test_string[] = "TEST"; /* string to test */
char *pStr = NULL; /* pointer to string */
pStr = test_string;
toAlpha(pStr);
printf("%s\n", pStr);
return 0;
}
void toAlpha(char *arg)
{
int i = 0; /* counter - original string*/
int j = 0; /* counter - temp string */
/* check each character in original and save alphabetic characters only */
for ( i = 0; i < str_len(arg); i++ )
{
if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
*(arg + j++) = *(arg + i);
else
if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
*(arg + j++) = *(arg + i) - 'A' + 'a';
}
/* add a null character terminator */
*(arg + j) = '\0';
}
int str_len(char *arg)
{
/*return count of letters in a C string */
int i = 0;
if ( arg != NULL )
while ( arg[i] != '\0' )
i++;
return i;
}
This is the non-working version with the failed attempt to use an array (it compiles but crashes at runtime):
#include <stdio.h>
void toAlpha(char*);
int str_len(char*);
void palindrome(char*);
int main()
{
char *test_strings[1]; /* strings to test */
char *pStr = NULL; /* pointer to string */
int i = 0; /* loop counter */
test_strings[0] = "TEST1";
test_strings[1] = "TEST2";
for (i = 0; i < 1; i++){
pStr = test_strings[i];
toAlpha(pStr);
printf("%s\n", pStr);
}
return 0;
}
void toAlpha(char *arg)
{
int i = 0; /* counter - original string*/
int j = 0; /* counter - temp string */
/* check each character in original and save alphabetic characters only */
for ( i = 0; i < str_len(arg); i++ )
{
if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
*(arg + j++) = *(arg + i);
else
if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
*(arg + j++) = *(arg + i) - 'A' + 'a';
}
/* add a null character terminator */
*(arg + j) = '\0';
}
int str_len(char *arg)
{
/*return count of letters in a C string */
int i = 0;
if ( arg != NULL )
while ( arg[i] != '\0' )
i++;
return i;
}