1

Why can't I add name into the data function?

If I run this code

data->userName = name;

that line is an error. Why can't I set userName to name?

#import <Foundation/Foundation.h>
typedef struct User {
    char userName[5];
    int  userAge;
} User;
int roomNum = 0;
void data (User* data, int age, char* name);

main () {
    int age;
    char name[5];
    User list[10] = {};
    for (int i = 0; i<3; i++) {
        scanf("%d",&age);
        scanf("%s",name);

        data(&list[roomNum],age,name);
        roomNum ++;
    }

    NSLog(@"%d   %s",list[0].userAge,list [0].userName);
    NSLog(@"%d   %s",list[1].userAge,list[1].userName);
    NSLog(@"%d   %s",list[2].userAge,list[2].userName);
}

void data (User* data, int age, char* name){
    NSLog(@"%s",name);
    (*data).userAge = age;
    data->userName = name;
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 1
    Use `strcpy` to copy strings. – VHarisop Jan 23 '15 at 18:31
  • strcpy is the only way to solve the problem? – yongjoon oh Jan 23 '15 at 18:32
  • 2
    Other ways are `sprintf()` and `strncpy()` and `memcpy()` but `strcpy()` is usual. – Weather Vane Jan 23 '15 at 18:33
  • 1
    Please check [this](http://stackoverflow.com/questions/6901090/c-why-is-strcpy-necessary) link. As is explained in AndreyT's answer, arrays in C are non-assignable (with only a few notable exceptions). – VHarisop Jan 23 '15 at 18:34
  • Use `strcpy()`, or preferably `strncpy()` or even better, `strlcpy()` to copy data between strings. You are attempting to do a shallow copy via the assignment operator, which is not going to generate the results you want. Also, considering using a macro to determine maximum buffer sizes (ie: `#define BUF_SIZE 255 .... char name[BUF_SIZE]`, unless you plan to dynamically allocate memory for strings with `calloc`, `malloc`, or `strdup`. – Cloud Jan 23 '15 at 18:35
  • oh thank you for answering my question. but is there any way to solve this problem without using function? – yongjoon oh Jan 23 '15 at 18:35
  • Of course - roll your own. But the libraries are there for a good reason – Weather Vane Jan 23 '15 at 18:35
  • Best course of action: Get a "C" programming language book and take some time to sturdy the language. – zaph Jan 23 '15 at 18:39

1 Answers1

1

I'd recommend one correction, instead of this

scanf("%s",name);

try with this

scanf("%4s",name);
  /*    ^ should be sizeof(name) - 1 */

so you prevent overflowing name, and to store the value in the struct instead of

data->userName = name;

use

strcpy(data->userName, name);

also, why are you doing this

(*data).userAge = age;

use consistent syntax either stick to the previous line, or

data->userAge = age;
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97