Вопрос

I am trying to use a variable and erase it just after a function used it. Basicacly I'm doint str1+str2, using it in a function and then freeing the memory. I thought I got everything straigth but my code throw me warnings and an error:

  1. ERROR: redefinition of 'commande'.
  2. Warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
  3. Warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]
  4. Warning: implicit declaration of function 'free' [-Wimplicit-function-declaration]
  5. Warning: incompatible implicit declaration of built-in function 'free' [enabled by default]

Here is the aforementioned code:

// Step 1
char* commande = (char*) malloc(len1 + len2 + 1);
strcpy(commande, str1);
strcat(commande, str2);
function(commande);
free(commande);
// Step 2
char* commande = (char*) malloc(len3 + len4 + 1);
strcpy(commande, str3);
strcat(commande, str4);
function(commande);
free(commande);

What am I doing wrong?

Edit: I corrected the typo in len2.

Это было полезно?

Решение

A statement such as

char* commande = (char*) malloc(len3 + len4 + 1);

is a variable declaration. It says the compiler: I want commande to be a pointer to a character. You can declare variables only once in a function, as it wouldn't make any sense to redeclare a variable.

The errors about incompatible implicit definitions come from the fact that you didn't tell the compiler what type malloc has. To do that, you have to include a header file that contains all neccessary declarations. Place the following line on top of your file:

#include <stdlib.h>

Другие советы

Make sure you've included and there is no need to declare the pointer commande after line2.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top