Initialize char array to hold non-null-terminated string

<>

This question already has an answer here:

Answers


No.

A string literal is a C-string which, by definition, is NULL-terminated.

Either ignore the final character, revisit your requirements (why do you care about a final character?!) or … I dunno, something else. Perhaps generate the objects with xxd?


I would do:

size_t length = 45;
char s[] = "The actual string is much longer then this..";
s[length - 1] = ".";

See what you have there has a trade-off between readability and functionality and I think that you can get away easily with this, since you can not avoid the NULL terminating string in the "normal" initialization.


If I were in your shoes, I would re-consider my approach and use std::string.


The terminating nul will be omitted if it doesn't fit. Since your strings are all fixed length, that's not a problem to arrange. For example:

#include <stdio.h>

char foo[3][4] = { "four", ".by." , "3333" };

int main(void)
{
    for (int i = 0; i < 3; ++i)
    {
         for (int j = 0; j < 4; ++j)
             putchar(foo[i][j]);
         putchar('\n');
    }
}

No. If you want essy to write code, copy to a second array but miss off the last char. You can use a char pointer in the first case to perhaps save some memory


There is no way to have a string literal not null terminated.

But you actually want to pack a number of strings densely and you know both the sizes and the strings at development time.

Assume:

"First"

"Second"

"Third"

to pack them you can safely do:

char const s[] = "First""Second""Third";

You only need to save lengths and properly reconstruct termination in case you want to print or use std string. That is easy though.

As a bonus you have saved from the excess pointer you would have to store for each and everyone string needed.


Need Your Help

Cannot build cordova project successfully error while executing ant debug command

android cordova netbeans-7

I was having an error that is Camera not successful invoked on first try (click) so I tried this solution on stackoverflow Phonegap(3.0.0) Camera not successful on first try.

Should you include or ignore gradle-wrapper.properties

git gradle android-gradle-plugin

When working on a team of android developers using gradle as your build system. Should you include gradle/wrapper/gradle-wrapper.properties in git, or should it be part of your .gitignore?