how to assign a value to a string array?

后端 未结 3 881
情深已故
情深已故 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:42

    You can't assign strings like that in C. Instead, use strcpy(substr[0], "abc"). Also, use %s not %d in your printf

    0 讨论(0)
  • 2020-12-19 19:45

    Hope this helps:

    void main(void)
    {
        char* string[10];
        string[0] = "Hello";
    }
    

    Otherwise I think ya need to copy it by hand or use strcpy or the like to move it from one block of memory to another.

    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    
    #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 <stdlib.h>, why include it?

    I suggest researching string literals, the functions available in <string.h> 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.

    0 讨论(0)
提交回复
热议问题