You have some problems with your code and with what you want.
A const char* string;
declares a pointer to char
. You can change the location of
where your pointer is pointing, you cannot change the contents of the memory
pointed to by the pointer.
const char *string = "Hello";
char line[] = "a b c";
string = "World"; // legal
string[0] = 'w'; // illegal
string = line; // legal
string[0] = 'A'; // illegal
So using a const char*
for reading input with scanf
& Co is pointless.
When I change to char *info
instead of const char
, I get the error:
Did you mean change from char *info
to const char
? That is even worse,
info
could hold one character only.
Please don't ignore the compiler warnings and don't silence them. The compiler
is telling
warning: variable 'info' is uninitialized when used here
You also are doing
const char *info;
...
sscanf(line, "%s", info);
Let's forget about the const
for a moment, let's pretend it's not there.
info
is an uninitialzed pointer, that means it points to nowhere in
particular. Passing it to sscanf
yields undefined behaviour, because sscanf
is trying to write into a memory location where you may or may not have access
to.
How to fix it:
char info[100];
...
sscanf(line, "%s", info);
info
is now an array of char
that can hold strings with maximal length of 99
characters.
Note that having a const
pointer where you want to save input from the user,
makes no sense, it cannot be constant by design, because the user input will
modify it.
It is perfectly fine to do the other way round: to use a const char*
for a
non-cost char*
, useful when you need to call a function that takes a const char*
for an argument:
#include <stdio.h>
void foo(const char *txt)
{
if(txt == NULL)
return;
printf("The text passed is: \"%s\"\n", txt);
}
int main(void)
{
char line[] = "Hello world";
foo(line);
return 0;
}