Modifying a String (char array) [closed]

老子叫甜甜 提交于 2021-01-28 03:23:00

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/60281429/modifying-a-string-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!