简体   繁体   中英

how to assign a value to a string array?

for example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char substr[10][20];

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

    printf("%d", substr[0]);
}

of course above is wrong? how to do it? thanks

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM