#include <stdio.h>
#include <string.h>
int main ()
{
int i, containizioa,lenstringa;
char stringa[20], stringhemin3[20], strG[30];
containizioa = 0;
for (i = 0; i < 7; i++)
{
printf("Inserisci una stringa\n");
scanf("%s", stringa);
if (strcmp(stringa[0], "a"))
{
containizioa++;
}
lenstringa = strlen(stringa);
if (lenstringa <= 3)
{
strcat(stringhemin3, " ");
strcat(stringhemin3, stringa);
}
if (strcmp(stringa[0], "g"))
{
strcat(strG, "_");
strcat(strG, stringa);
}
}
printf("Le stringhe di lunghezza inferiore o uguale a 3 sono: %s\n",stringhemin3);
printf("Il numero di stringhe che iniziano per a è: %d\n", containizioa);
printf("Le stringhe che iniziano per g sono: %s", strG);
return 0;
}
This is my code, it’s supposed to get the first char of the string “stringa” so then i can show all the strings that start with “g” but when I compile this error appears:
warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
I tried removing the “[0]” but then the code counted all strings with “g” in it, and also tried replacing it with [1] but the same thing happened.
Many issues
-
stringa[0]
haschar
type and it is an integer.strcmp
requires pointer to char. -
strcmp
comparesC
strings so the wholestringa
has to be"g"
(so it will not work for “gamma”).
To see if the particular character of string (in this case first) is equal to a specific character simply:
if (stringa[0] == 'g'))
You do need any functions for that.
You can of course use strcmp
for it if you use compound literals (it is a very weird way 😊):
if (!strcmp((char []){stringa[0],0}, "g"))
Just fix typo, !strncmp(&stringa[0], "a", 1)
, !strncmp(&stringa[0], "g", 1)
instead of strcmp(stringa[0], "a")
, strcmp(stringa[0], "g")
.
strcmp
returns 0, if strings are equal.
strcmp(stringa[0], "a")
is incorrect. This compares one character to a string. Do you meanif (stringa[0] == 'a')
? Note the different quotes used.OT:
strcat(stringhemin3, " ");
The bufferstringhemin3
is uninitialised, making this operation unpredictable. (Same forstrG
.) AND, it seems 7 iterations of max length 3 plus extra SP (ie: 4) might have yielded a string requiring 28+1 bytes…stringhemin3[20]
isn’t big enough, and this will cause undefined behaviour.)