3

I have recently started to code in C and I am having quite a lot of fun with it. But I ran into a little problem that I have tried all the solutions I could think of but to no success. How can I assign a char* variable to an array?

Example

int main()
{
    char* sentence = "Hello World";

    //sentence gets altered...

    char words[] = sentence;

    //code logic here...

    return 0;
}

This of course gives me an error. Answer greatly appreciated.

Twahanz
  • 204
  • 1
  • 15
  • 1
    can you explain what you mean by "sentence gets altered" (showing code would be good) – M.M Jun 12 '16 at 09:30
  • 1
    Check this [question](http://stackoverflow.com/questions/3172075/segmentation-fault-reversing-a-string-literal). If by _sentence gets altered_ you mean you try to change the string then you have another problem with the code. –  Jun 12 '16 at 09:55
  • @DmitryKuznetsov Thank you for pointing that out (pun unintended). I just realized that I can't change the value of the pointer. – Twahanz Jun 12 '16 at 10:02
  • In C arrays cannot not get assigned something. – alk Jun 12 '16 at 10:31
  • 1
    char *sentence should be const char *sentence – Michi Jun 12 '16 at 11:05
  • @Twahanz you can change the value of the pointer, but not the characters being pointed to (before changing the value of the pointer, that is) – M.M Jun 12 '16 at 20:50

7 Answers7

2
  1. You need to give the array words a length

    char words[100]; // For example
    
  2. The use strncpy to copy the contents

     strncpy(words, sentence, 100);
    
  3. Just in case add a null character if the string sentence is too long

     words[99] = 0;
    
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

Turn all the compiler warnings on and trust what it says. Your array initializer must be a string literal or an initializer list. As such it needs an explicit size or an initializer. Even if you had explicitly initialized it still wouldn't have been assignable in the way you wrote.

 words = sentence;

Please consult this SO post with quotation from the C standard.

As of:

How To Assign char* to an Array variable ?

You can do it by populating your "array variable" with the content of string literal pointed to by char *, but you have to give it an explicit length before you can do it by copying. Don't forget to #include <string.h>

char* sentence = "Hello World";
char words[32];                //explicit length
strcpy (words, sentence);
printf ("%s\n", words);

Or in this way:

char* sentence = "Hello World";
char words[32];
size_t len = strlen(sentence) + 1;
strncpy (words, sentence, (len < 32 ? len : 31));
if (len >= 32) words[31] = '\0';
printf ("%s\n", words);

BTW, your main() should return an int.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24
  • BTW `strncpy` would be better to prevent buffer overruns – Ed Heal Jun 12 '16 at 09:34
  • @EdHeal strncpy has its own set of problems, you can replace a buffer overrun of one sort with another . IMHO it should almost never be used – M.M Jun 12 '16 at 09:35
  • @M.M - It is certainty better than `strcpy`. It can be used without danger if used properly as the length of `dest` is known to the programmer at compile time – Ed Heal Jun 12 '16 at 09:37
  • 1
    @EdHeal disagree, both can be used without danger if used properly, and both can be used badly. `strcpy` is very straightforward – M.M Jun 12 '16 at 09:38
  • 1
    @M.M _ Of course I agree that both can be used without danger if used skillfully. But it is easier IMHO to make a mistake with `strcpy` as the `src` can come from multiple routes – Ed Heal Jun 12 '16 at 09:40
  • Great comments. Thanks for contributing. – user3078414 Jun 12 '16 at 09:45
  • The code as shonw will fail for `strlen(sentence)` returning more then 31 as this would leave `words` without `0`-termination. `strncpy()` is a beast. – alk Jun 12 '16 at 10:28
  • Thanks for your attention, @alk, my copy-paste error, sorry, fixed now. – user3078414 Jun 12 '16 at 14:27
0

I think you can do it with strcpy :

#include <memory.h>
#include <stdio.h>
int main()
{
    char* sentence = "Hello World";
    char words[12];
    //sentence gets altered...
    strcpy(words, sentence);
    //code logic here...
    printf("%s", words);
    return 0;
}

..if I didn't misunderstand. The above code will copy the string into the char array.

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
0

How To assign char* to an Array variable?

The code below may be useful for some occasions since it does not require copying a string or knowing its length.

char* sentence0  = "Hello World";
char* sentence1  = "Hello Tom!";

char *words[10]; // char *words[10] array can hold char * pointers to 10 strings

words[0] = sentence0;
words[1] = sentence1;

printf("sentence0= %s\n",words[0]);
printf("sentence1= %s\n",words[1]);

Output

sentence0= Hello World
sentence1= Hello Tom!
sg7
  • 6,108
  • 2
  • 32
  • 40
0

The statement

char* sentence = "Hello World";

Sets the pointer sentence to point to read-only memory where the character sequence "Hello World\0" is stored.

words is an array and not a pointer, you cannot make an array "point" anywhere since it is a fixed address in memory, you can only copy things to and from it.

char words[] = sentence; // error

instead declare an array with a size then copy the contents of what sentence points to

char* sentence = "Hello World";
char words[32];
strcpy_s(words, sizeof(word), sentence); // C11 or use strcpy/strncpy instead

The string is now duplicated, sentence is still pointing to the original "Hello World\0" and the words array contains a copy of that string. The array's content can be modified.

AndersK
  • 35,813
  • 6
  • 60
  • 86
  • @alk just an arbitrary value to contain "Hello World", sounded like he wanted to modify it so added some more bytes. – AndersK Jun 13 '16 at 08:30
0

Among other answers I'll try to explain logic behind arrays without defined size. They were introduced just for convenience (if compiler can calculate number of elements - it can do it for you). Creating array without size is impossible.

In your example you try to use pointer (char *) as array initialiser. It is not possible because compiler doesn't know number of elements stayed behind your pointer and can really initialise the array.

Standard statement behind the logic is:

6.7.8 Initialization

...

22 If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. At the end of its initializer list, the array no longer has incomplete type.

Dmitry Poroh
  • 3,705
  • 20
  • 34
-1

I guess you want to do the following:

#include <stdio.h>
#include <string.h>

int main()
{
char* sentence = "Hello World";

//sentence gets altered...

char *words = sentence;
printf("%s",words);

//code logic here...

return 0;

}

Flying disk
  • 120
  • 7
  • 1. No need to cast `malloc()`; 2. The code misses to allocate space for the `0`-terminator; 3. `words=sentence;` leaks the memory allocated in the line before. – alk Jun 12 '16 at 12:57
  • 1
    The question was about "*how to populate an array*". There is no array in the code you show. – alk Jun 12 '16 at 13:04
  • @alk and you can access characters in words using words[0],words[6],words[8], don't you think it is more like an array. Array name in c is nothing but the base address of the contiguous memory loacation and arr[i] is nothing but *(arr+i). Isn't words here more like an array? – Flying disk Jun 12 '16 at 13:15
  • No, `words` is a `char*`, that is a pointer and not an array. `char s[42];` would define an array. Array are not pointers and pointers are not arrays. Sure, arrays sometimes "decay" to pointers, also the indexing-operators works on both. But still this does not make them the same. – alk Jun 12 '16 at 13:23