1

Here is my code:

#include <stdio.h>
#include<stdlib.h>
char *s = (char *)malloc (40);
int main(void)
{
    s="this is a string";
    printf("%s",s);
}

I am getting the following error:

error: initializer element is not constant char *s = (char *)malloc (40);

mtszkw
  • 2,717
  • 2
  • 17
  • 31

3 Answers3

2

You don't need to allocate memory in this way if you wanna initialize it in code, I mean:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *s = "this is a string"; // char s[] = "this is a string";
    printf("%s",s);

    return 0;
}

is just enough in this case. If you really want to assign const char string to your char array, this topic should enlighten you: Dynamically allocating memory for const char string using malloc()

Community
  • 1
  • 1
mtszkw
  • 2,717
  • 2
  • 17
  • 31
2

You cannot not do that.

You can do this instead -

#include <stdio.h>
#include<stdlib.h>
#include <string.h>
char *s;                    // probably should avoid using global variables
int main(void)
{
      s=malloc(40);
      strcpy(s,"this is a string");
      printf("%s",s);
      free(s);
}

Other than this inside main you can do this -

char *s="this is a string";    //string literal you can't modify it

Or

char s[]="this is a string";    // modifiable string
ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

You assign a pointer to a string constant to a variable, s, which is not declared to point to a constant. This is what you want:

#include <stdio.h>

int main(void)
{
   const char *s = "this is a string";

   printf("%s\n", s);
   return 0;
}

In C there are basically three ways to declare "string" variables.

String constant pointers

If you need a name for a string that will not change, you can declare and initialize it like

const char *s = "a string";

Character arrays

If you need a string variable and you know in advance how long it needs to be you can declare and initialize it like

char s[] = "a string";

or like

char s[9];

strcpy(s, "a string");

Character sequence pointers

If you don't know in advance how large the array needs to be, you can allocate space during program execution:

char *s;

s = malloc(strlen(someString) + 1);
if (s != NULL) {
   strcpy(s, someString);
}

The "+1" is to make room for the null character (\0).

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60