I am trying to modify a string in C language
char signal_cat[8];
if (k == 1) {
strcpy_s(signal_cat, "HPHA",6); //why cant I change char array (string) values???
}
else if (k == 2) {
strcpy_s(signal_cat, "Normal",6);
}
printf("Original signal category: %s \n", signal_cat);
When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"
I have tried
signal_cat = "HPHA";
too, but an error shows "expression must be a modifiable lvalue"
Does anyone know how I can go about doing this?
Are you using Visual Studio to compile your C code?
If you are and the compiler is forcing you to use strcpy_s()
instead of strcpy()
, you can still use the standard library function strcpy()
by defining the following macro at the top of your source file:
#define _CRT_SECURE_NO_WARNINGS
The actual problem in your code is that you are giving the arguments to strcpy_s() in the wrong order. Check the function's prototype to provide the arguments in the correct order.
You specified an invalid order of arguments. A call of strcpy_s should look like
strcpy_s(signal_cat, sizeof( signal_cat ), "HPHA" );
Otherwise use the standard C function strcpy
like
strcpy( signal_cat, "HPHA" );
provided that the array signal_cat has enough space to accommodate the string literal.
Or you can use another standard function strncpy
strncpy( signal_cat, "HPHA", sizeof( signal_cat ) );
signal_cat[sizeof( signal_cat )-1] = '\0';
As for this statement
signal_cat = "HPHA";
then arrays do not have the assignment operator. They are non-modifiable lvalues.
What is strcpy_s? Do you have a prototype for it in your code (ie. have you included the correct files for declarations?) What are its arguments, and why are you using it?
You are obviously learning C; it is not in your best interest to start with some vendors proprietary (and often bizarre) extensions? Learn the language, learn its established (standard) interfaces, then, if absolutely necessary, endure some vendors twisted extensions is a good process to follow:
#include <string.h>
#include <stdio.h>
int main(void) {
char signal_cat[8];
strncpy(signal_cat, "HPHA", sizeof signal_cat);
printf("%s\n", signal_cat);
strncpy(signal_cat, "Normal", sizeof signal_cat);
printf("%s\n", signal_cat);
return 0;
}
User contributions licensed under CC BY-SA 3.0