سؤال

I have to save how many letters, numbers, whitespaces and lines there are in a string:

char string[2048];
...
string = "aaa 111\nsas 23 d\nds";
for(i = 0; i < strlen(string); i++){
    if (isdigit(string[i]) != 0){
        numbers++;
    } else if (isascii(string[i]) != 0){
        letters++;
    } ...
}

It gaves me many error, "incompatible types when assigning to type ‘char[2048]’ from type ‘char *’" and other errors

What's wrong in that code?

thank you, Lorenzo

هل كانت مفيدة؟

المحلول 3

char string[2048] = "aaa 111\nsas 23 d\nds";
n = strlen(string);
for(i = 0; i < n; i++){
    if (isdigit(string[i]) != 0){
        numbers++;
    } else if (isascii(string[i]) != 0){
        letters++;
    } ...
}

نصائح أخرى

Try,

char string[2048];

strcpy(string,"aaa 111\nsas 23 d\nds");

or

char string[2048] = "aaa 111\nsas 23 d\nds";

Instead of

char string[2048];

string = "aaa 111\nsas 23 d\nds";

Short version

You declared string as an array of size 2048 of char:

char string[2048];

This line is causing troubles because you assign a char* which is a pointer:

string = "aaa 111\nsas 23 d\nds";

Try the following command which will iterate over the char* and copy the element until reaching the end of the string:

strcpy(string, "aaa 111\nsas 23 d\nds");

If you just want to give an initial value to this char[], use:

char string[2048] = "aaa 111\nsas 23 d\nds";

Long version

What you do is kind of ok in this case but in practice, it can be dangerous to use fixed size arrays of chars. If you were to try to copy a string over 2048 chars you would be writing after the space allocated for this variable.

The reason you cannot just assign is that they are array of chars, it is not an operation really defined in C, the char[2048] is only kind of a pointer on a space of length 2048*sizeof(char). strcpy() will iterate on the second argument and copy the characters until finding 0 which will mark the end of your string.

You may want to check strncpy() as it is safer in the case you have a string larger than the buffer. From the man page:

The stpncpy() and strncpy() functions copy at most n characters from s2 into s1. If s2 is less than n characters long, the remainder of s1 is filled with `\0' characters. Otherwise, s1 is not terminated.

Use strcpy instead of assigning like string = "aaa 111\nsas 23 d\nds"; or initialize string array as char string[2048] = "aaa 111\nsas 23 d\nds";.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top