struct updaten wenn leer?

lano

Aktives Mitglied
Moin.

Ich versuche ein struct mit daten zu befüllen wenn sie leer sind.
Aber irgendwie will das nicht so wie ich das will.

Ich hab da ma was vorbereitet...
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

struct config {
  int zahl;
  char string[40];
};

struct config update_conf(struct config conf) {
  if (conf.zahl != 0)
    conf.zahl = 100;
  if (strcmp(conf.string, "") == 0)
    strcpy(conf.string, "Hallo");
  return conf;
}

void print_conf(struct config conf) {
  printf("zahl: %d\n", conf.zahl);
  printf("string: %s\n", conf.zahl);
}

int main(int argc, char *argv[], char *envp[]) {

  struct config conf = {.zahl = 0, .string = ""};

  conf = update_conf(conf);

  print_conf(conf);

  return EXIT_SUCCESS;
}

Kann mir das jemand erklären ?
 
if (conf.zahl != 0) conf.zahl = 100;
conf.zahl == 0, oder?

printf("string: %s\n",conf.zahl);
Nope. conf.string.

Und um Himmels Willen kopiere die Strukturen nicht in die Funktionen!
C:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct config {
    int zahl;
    char string[40];
};


void update_conf(struct config *conf){
    if (conf->zahl == 0) conf->zahl = 100;
    if (*conf->string == '\0') strcpy(conf->string,"Hallo");
}


void print_conf(const struct config *conf) {
    printf("zahl: %d\n",conf->zahl);
    printf("string: %s\n",conf->string);
}


int main (int argc, char *argv[], char *envp[]) {

    struct config conf = {
        .zahl = 0,
        .string = ""
    };

    update_conf(&conf);

    print_conf(&conf);

    return EXIT_SUCCESS;
}
 
Zurück
Oben Unten