how to assign a value to a string array?

后端 未结 3 886
情深已故
情深已故 2020-12-19 19:25

for example

#include 
#include 
#include 

char substr[10][20];

int main() {
    substr[0] = \"abc\";

    pr         


        
3条回答
  •  星月不相逢
    2020-12-19 19:57

    I hate giving 'full' answers to homework questions, but the only way to answer your question is to show you the answer to your problem, because it is so basic:

    #include 
    #include 
    
    #define MAXLEN 20
    
    char substr[10][MAXLEN];
    
    int main(void) {
            strncpy(substr[0], "abc", MAXLEN);
            puts(substr[0]);
            return 0;
    }
    

    Your code (as is) has several faults:

    • You are treating substr[0] as a string literal. You can't do that.
    • You were using printf formatters incorrectly. %s is for strings
    • You don't need to bother printf() to print a string
    • You should (in real code) watch out for buffer overflows, hence strncpy()
    • If main() doesn't want / need argc and argv, its arguments should be void
    • main() should return a value, as its return type is int
    • You aren't using anything out of , why include it?

    I suggest researching string literals, the functions available in as well as format specifiers.

    Also note, I am not checking the return of strncpy(), which is something you should be doing. That is left as an exercise for the reader.

提交回复
热议问题