bluesshead
bluesshead

Reputation: 45

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

Upvotes: 1

Views: 71

Answers (2)

ad absurdum
ad absurdum

Reputation: 21321

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().

Upvotes: 1

Havenard
Havenard

Reputation: 27884

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.

Upvotes: 2

Related Questions