0

I have this part in a code:

char* data="My name is: "; 

I would like to add to this the argv[1] argument with represents a name. How to do this in c code? I've tried strcpy and strcat but i have segmentation fault when Ipcp do this:

strcpy(data,argv[1]); 

Can anyone please help?

Also why this: data=data+argv[1] is not working?

1

4 Answers 4

4

You need to provide some memory, where the result of the concatentation can be stored into. For example:

char buffer[1024]; strcpy(buffer, "My name is: "); strcat(buffer, argv[1]); 

Note, however, that this is error prone: if the value of argv[1] combined with the prefix string is longer than 1024 characters, this produces a buffer overflow. So, maybe something like this:

char* prefix = "My name is: "; int length = strlen(prefix) + strlen(argv[1]) + 1; char* buffer = malloc(length); if (!buffer) abort(); else { strcpy(buffer, prefix); strcat(buffer, argv[1]); /* Do something with buffer here. And don't * forget to free it, once you no longer need * it. This is C -- no garbage collection. */ free(buffer); } 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the detailed examples. You can also use strncpy/strncat to avoid buffer overflows.
0

Also why this: data=data+argv[1] is not working?

About this one - in C data and argv are nothing more than pointers to address in the memory containing your string. You can't concatenate strings(char*) this way. I suggest to take a look at the string library and maybe a bit more in C as a whole.

Comments

0

Memory for data will be allocated in read-only section. so modifying will cause issue.

where in memory are string literals ? stack / heap?

+ operator will not do concat as you thought.

strcat() function is implemented in string.h.

Comments

0

You cant append to th data pointer because there are no space in it

char result_data [1024]; char* data="My name is: "; strcat(result_data, data); strcat(result_data, argv[1]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.