I am trying to replace all lowercase letters by their uppercase counterpart without using other functions available in the C standard library and using pointers. I have my main.c:
#include <stdio.h>
#include "upper1.h"
int main() {
char string[] = "HelloWorld";
int arraySize = sizeof(string) / sizeof(string[0]);
printf("String before transformation: ");
int i;
for (i= 0; i< arraySize; i++) {
printf("%c", string[i]); //prints array information
}
printf("\n");
char *str = string; //pointer that points to the array
upper1(str);
printf("String before transformation: ");
int j;
for (j= 0; j< arraySize; j++) {
printf("%c", string[i]); //prints array information
}
printf("\n");
return 0;
}
And I have my function code file:
void upper1(char *str) {
int i;
for(i = 0; i < 10; i++) {
if(*str >= 65 + 32 && *str <= 90 + 32) { //65+32 is "a" and 90+32 is "z"
*str = *str - 32;
}
str++;// skips one position of the array
}
}
For some reason when I run I get:
gcc -g -Wall -c upper1.c -o upper1.o gcc -g -Wall -c main.c -o main.o gcc upper1.o main.o -o ex04 ./ex04 String before transformation: HelloWorld String before transformation: �����������
Instead of
gcc -g -Wall -c upper1.c -o upper1.o gcc -g -Wall -c main.c -o main.o gcc upper1.o main.o -o ex04 ./ex04 String before transformation: HelloWorld String before transformation: HELLOWORLD
(I have a file "upper1.h" but that's correct only with: void upper1(char *str);
)
It's because you're using i
in your second loop instead of j
.
printf("String before transformation: ");
int j;
for (j = 0; j < arraySize; j++) {
printf("%c", string[j]); // use 'j' instead of 'i'
}
You can avoid a typo like this in the future by declaring your loop counter inside the for-loop. This ensures the counter is only accessible within the scope of the loop and can't be reused in another loop:
printf("String before transformation: ");
for (int j = 0; j < arraySize; j++) {
printf("%c", string[j]);
}