简体   繁体   中英

C - Copying a char to another

I am a beginner in C language. I want to copy a char array to another, but I cannot. I got these errors:

Line 10 - [Warning] passing argument 1 of 'insert' makes pointer from integer without a cast
Line 4 - [Note] expected 'char *' but argument is of type 'char'

Can you help me with finding the errors in this code?

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

void insert(char d[100]);

int main( ) {

    char m[100];
    scanf("%s", &m);
    insert(m[100]);
    return 0;
}

void insert (char d[100]) {
    char s[200];
    strcpy(s, d); 
}

You should pass m to insert() not m[100] . In that context, m[100] represents a single element of the m array and not the array itself. That's why the "integer to pointer without a cast" warning, because char is an integer after all.

The function signature of main() should be one of:

int main(void) {}

or

int main(int argc, char *argv[]) {}

or equivalently,

int main(int argc, char **argv) {}

There is no need to use the address operator & with an array argument in scanf() , since arrays decay to pointers to their first elements in most expressions, including function calls.

Note that you should specify a maximum field width when using the %s conversion specifier with scanf() to avoid buffer overflows:

scanf("%99s", m);

It is adquate to declare the insert() function as:

void insert(char d[]);

When you call the insert() function, only use the name of the array that you want to pass as an argument; this will decay to a pointer to the first element of the array. It is worth pointing out that the original code had undefined behavior with:

insert(m[100]);

This attempts to access the element at index 100 of the array m[] , which is out of bounds.

The code now looks like this:

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

void insert(char d[]);

int main(void)
{
    char m[100];
    scanf("%99s", m);
    insert(m);

    return 0;
}

void insert (char d[])
{
    char s[200];
    strcpy(s, d);
}

Now, I don't know what you intend to do with the copied string s , but it no longer exists after insert() returns control to main() .

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