问题描述
我试图用大写字母替换所有小写字母,而不使用C标准库中提供的其他功能和使用指针。 我有我的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;
}
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
}
}
由于某种原因,我得到:
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 转换前的字符串:HelloWorld 转换前的字符串:����������
代替
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 转换前的字符串:HelloWorld 转换前的字符串:HELLOWORLD
(我有一个文件“ upper1.h”,但这仅适用于void upper1(char *str);
)
解决方法
这是因为您在第二个循环中使用DDM
而不是i
。
j
您可以通过在for循环内声明循环计数器来避免这种错字。这样可以确保计数器只能在循环范围内访问,并且不能在另一个循环中重复使用:
printf("String before transformation: ");
int j;
for (j = 0; j < arraySize; j++) {
printf("%c",string[j]); // use 'j' instead of 'i'
}