循环使用Const Char

Nat*_*pos 0 c loops const constants char

我需要循环一个const char,我使用了一个简单的字符串循环示例:

const char *str;
for(int i = 0; i < 10; ++i)
{
   str += " ";
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译时,我得到了这个:

ubuntu @eeepc:〜/ Test_C_OS $ gcc -o kernel.o -c kernel.c -Wall -Wextra -nostdlib -nostartfiles -nodefaultlibs
kernel.c:26:error:'for'循环初始声明在C99模式
kernel.c 之外使用:28:错误:无效的操作数到二进制+
ubuntu @ eeepc:〜/ Test_C_OS $

我该怎么办?

caf*_*caf 5

你的第一个错误是因为你做了:

for (int i = 0; ...
Run Code Online (Sandbox Code Playgroud)

代替:

int i;
for (i = 0; ...)
Run Code Online (Sandbox Code Playgroud)

(或者,您可以单独留下该位并添加-std=gnu99到您的gcc选项中).

你的第二个错误是因为这行:

   str += " ";
Run Code Online (Sandbox Code Playgroud)

尝试添加两个指针值.这在C中没有任何定义的语义 - 它没有任何意义.你在这里尝试做什么甚至都不是特别清楚- 也许你想从一个空字符串开始,然后将10个字符串附加" "到它?如果是这样,那么您需要将其更改为:

char str[100]; /* Allocate space for a 99 character string, plus terminator */
int i;

str[0] = '\0'; /* Start with empty string */
for (i = 0; i < 10; i++)
{
    strcat(str, " ");
}
Run Code Online (Sandbox Code Playgroud)

在这种特殊情况下,因为你总是循环10次你根本不需要一个循环 - 你可以只使用10个空格的字符串:

char str[100];

strcpy(str, "          "); /* 10 spaces */
Run Code Online (Sandbox Code Playgroud)

(这str[0] = '\0';是不必要的,因为我们现在正在使用strcpy,而不是strcat).