0
//Função de inversão de String.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
char* invertStr(char *source)
{
int size = strlen(source);
char *inverted = malloc(sizeof(source) * (size + 1));
int count = size;
for (int i = 0; i < size; i++)
{
inverted[i] = source[count];
count--;
}
inverted[size + 1] = ('\0');
return inverted;
}
int main(void)
{
char str[SIZE];
char str2[SIZE];
scanf("%29s", str);
char *inverted = invertStr(str);
if (inverted == 0)
{
printf("NULL Pointer. Memory alocation error");
return -1;
}
strcpy(str2, inverted);
printf("%s | %s\n", str, str2);
free(inverted);
return EXIT_SUCCESS;
}
The output of the second string is not displayed successfully.
Code running on ideone.
Yet you are allocating too much space. I think it should be:
char *inverted = malloc(sizeof(char) * (size + 1));
– anonimo
@anonimo I see no difference...
*source == char
.source
is a pointer, will have 4 or 8 bytes depending on the architecture,*source
is whatsource
points out that in this case it is achar
– vmp
The guy
char
takes 1 byte, and a pointer - as you said yourself - takes 4 or 8 bytes.– anonimo
@anonymity
source
is a pointer.*source
is a char.– vmp
@anonymity
sizeof(char)
andsizeof(*source)
are equivalent. Thanks for the contribution, guys. Zero Based Arrays + Null Terminator confuse me a lot, I need to practice more, in addition to better understand the operation and operands ofsizeof
– TiagoDM