Looping a Const Char

I need to loop a const char, and I've used a simple example of string loop:

const char *str;
for(int i = 0; i < 10; ++i)
{
   str += " ";
}

But when I tried to compile, I got this:

ubuntu@eeepc:~/Test_C_OS$ gcc -o kernel.o -c kernel.c -Wall -Wextra -nostdlib -nostartfiles -nodefaultlibs kernel.c:26: error: ‘for’ loop initial declaration used outside C99 mode kernel.c:28: error: invalid operands to binary + ubuntu@eeepc:~/Test_C_OS$

What should I do?

Answers


Your first error is because you have done:

for (int i = 0; ...

instead of:

int i;
for (i = 0; ...)

(alternatively, you can leave that bit alone and add -std=gnu99 to your gcc options).

Your second error is because the line:

   str += " ";

attempts to add two pointer values. That doesn't have any defined semantics in C - it doesn't make any sense. It's not even particularly clear what you're trying to do here - perhaps you want to start with an empty string, then append 10 copies of the string " " to it? If so, then you need to change it to something like:

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, " ");
}

In this particular case though, because you're always looping 10 times you don't really need a loop at all - you can just use a string of 10 spaces:

char str[100];

strcpy(str, "          "); /* 10 spaces */

(The str[0] = '\0'; is unnecessary because we're now using strcpy, not strcat).


Need Your Help

WPF: Change HeaderedContentControl orientation

wpf orientation

Is there a way to change the orientation of the Header and the Content in a HeaderedContentControl?.

How to implement “equals” method for generics using “instanceof”?

java oop generics instance equals

I have a class that accepts a generic type, and I want to override the equals method in a non-awkward way (i.e. something that looks clean and has minimal amount of code, but for a very general use

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.