Im trying to remove the first char of the string and keep the remainder, my current code doesnt compile and im confused on how to fix it.
My code:
char * newStr (char * charBuffer)
{
int len = strlen(charBuffer);
int i = 1;
char v;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
for(i=1;i<len;i++)
v = v + charBuffer[i];
}
v = v + '\0';
return v;
}
Gcc: “Warning: return makes pointer from integer without a cast”
Also: “char * newStr (char * charBuffer)” needs to remain the same.
Strings don’t work like this in C. You’re summing up all of the characters in the buffer into the
vvariable. You can’t use + to concatenate. The code you posted has some serious problems which indicate that there’s an understanding gap with how to use C.Try this:
char *newStr (char *charBuffer) { int length = strlen(charBuffer); char *str; if (length <= 1) { str = (char *) malloc(1); str[0] = '\0'; } else { str = (char *) malloc(length); strcpy(str, &charBuffer[1]); } return str; }or this:
char *newStr (char *charBuffer) { char *str; if (strlen(charBuffer) == 0) str = charBuffer; else str = charBuffer + 1; return str; }Depending on whether you want to allocate a new string or not. You’ll also have to add the code for handling the cases that don’t start with ‘Q’ or ‘A’. I didn’t include those because I’m not sure exactly what you’re trying to do here.
Make sure you do some research into allocating and deallocating memory with malloc and free. These are fundamental functions to be able to use if you’re going to be doing C programming.