I'm using the C programming language in Visual Studio 2015, and I'm simply trying to prompt the user for three sentences of text that are then combined into one, three sentence paragraph. I just can't get my strcpy and strcat functions to work.
Thoughts??
Thank you so much in advance!
#include <string.h>
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MASTERSIZE 300
int main()
{
char *calcTotalMessage(char[100], char[100], char[100]);
#define MSIZE 100
#define MSIZEE 100
#define MSIZEEE 100
int read;
char message[MSIZE];
char m2[MSIZE];
char m3[MSIZE];
char* totalM;
printf("Enter a sentence:");
scanf_s("%s", &message);
printf("Enter another sentence:");
scanf_s("%s", &m2);
printf("Enter third sentence:");
scanf_s("%s", &m3);
totalM = calcTotalMessage(message, m2, m3);
printf(totalM);
return 0;
}
char *calcTotalMessage(char *m1, char *m2, char *m3)
{
void strcat(char, char);
void strcpy(char, char);
char *totalM = "";
strcpy(*totalM, *m1);
strcat(*totalM, *m2);
strcat(*totalM, *m3);
return totalM;
}
char *totalM = "";
So totalM points at a string literal. Modifying literals is disallowed by the C standard. You won't necessarily get a compile time error, but your program has undefined behavior. It's unlikely to behave properly.
strcpy(*totalM, *m1);
Then you attempt to pass strcpy a char (the type of *totalM and *m1), and not a pointer. That character is converted to some nonsensical pointer value that you attempt to write at. That again results in undefined behavior. You compiler even tried to warn you, but instead of heeding those errors you added declarations for functions that don't exist (strcpy(char, char)).
I suggest you pass the output buffer into calcTotalMessage instead of returning it.
void calcTotalMessage(char const *m1, char const *m2, char const *m3, char *output) {
output[0] = '\0';
strcpy(output, m1);
strcat(output, m2);
strcat(output, m3);
}
To be called like this:
char totalM[MSIZE + MSIZEE + MSIZEEE] = {'\0'};
calcTotalMessage(message, m2, m3, totalM);
A point regarding style. You won't usually see function declarations anywhere but at file scope. So don't get too used to declaring functions inside another function scope.
Related
I've looked around everywhere and tried pretty much everything suggested and can't get anything to work.
this is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
float a;
char *nums[3];
char str[5];
printf("Please enter a,b,c:");
scanf("%s",str);
int i=0;
char *p;
p = strtok (str,",");
while (p != NULL)
{
nums[i++] = p;
p = strtok (NULL, ",");
}
a=atof(nums[0]);
printf("%s\n",nums[0]);
printf("%f\n",a);
return 0;
}
the math.h is for something later on after I figure this out. So if I entered "1,2,3" into this program, my print statements would show me "1" and then "0.000", this is obviously just there for me to test things out but why the does my value just disappear after trying to convert to a float? I need that value of 1 to do math with later in my program but I can't get that char pointer value no matter what I try, I can only seem to print it, but it screws up as soon as I try to convert it into a type I can use.
Two issues:
You nums and str arrays are too short. nums should have a size of at least 3, and str should be at least 6 ("1,2,3" plus null byte), probably more for larger numbers.
So change those to:
char *nums[3];
char str[20];
Second, you don't #include <stdlib.h>, which contains the declaration of atof. Without a declaration, it is assumed to return an int.
Fix the array sizes, and #include <stdlib.h>, and it should work.
I am relatively new to C. I have encountered quite a few segmentation faults but I was able to find the error within a few minutes. However this one's got me confused. Here's a new function I was trying to write. This basically is the C equivalent of the python code
r=t[M:N]
Here's my C code with a test case
#include <stdio.h>
char* subarraym(char* a, int M, int N)
{
char* s;
int i;
for (i=M; i<N; i++){ s[i-M]=a[i]; }
return s;
}
main()
{
char* t="Aldehydes and Ketones";
char* r=subarraym(t,2,10);
printf("%c\n",r[4]);
return 0;
}
The expected answer was 'd'. However I got a segmentation fault.
Extra Info: I was using GCC
Your code will not work because your sub-array pointer is never initialized. You could copy the sub-array, but then you will have to manage the memory, and that's overkilling for your problem.
In C, arrays are usually passed around as pairs of pointer and number of elements. For example:
void do_something(char *p, int np);
If you follow this idiom, then getting a sub-array is trivial, assuming no overflow:
void do_something_sub(char *p, int np, int m, int n)
{
do_array(p + m, n);
}
Checking and managing overflow is also easy, but it is left as an exercise to the reader.
Note 1: Generally, you will not write a function such as do_something_sub(), just call do_something() directly with the proper arguments.
Note 2: Some people prefer to use size_t instead of int for array sizes. size_t is an unsigned type, so you will never have negative values.
Note 3: In C, strings are just like char arrays, but the length is determined by ending them with a NUL char, instead of passing around the length. So to get a NUL-terminated substring, you have to either copy the substring to another char array or modify the original string and overwrite the next-to-last char with the NUL.
From
...,10);
you expect to receive 10 char (+1 0-terminator), so provide it to the function somehow.
Not doing so, but writing to invalid memory by
char * s; /* note, that s is NOT initialised, so it points "nowhere". */
...
s[i-M] = ...
provokes undefined behaviour.
Possible solution to provide memory for such a case can be found in this answer: https://stackoverflow.com/a/25230722/694576
You need to secure the necessary memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* subarraym(char *a, int M, int N){
if(N < 0){
N += strlen(a);
if(N < 0)
N = 0;
}
int len = N - M;
char *s =calloc(len+1, sizeof(char));//memory allocate for substring
return memcpy(s, &a[M], len);
}
int main(){
char *t="Aldehydes and Ketones";
char *r=subarraym(t,2,10);
printf("%c\n",r[4]);
free(r);
return 0;
}
I am passing a C Macro to a function which receives it as char *. Without any reason the last character from macro gets truncated. I doubt some memory leak, but could not find where.
#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"
....
char file[_D_NAME_MAX + 1] = {'\0'};
....
funMove(file, FROM, TO);
....
....
int funMove(char *file, char *from, char *to) {
//here the to value is one character less (/some/local/path/to) slash got truncated
}
There's nothing wrong with the code you've shown us since the following works fine:
#include <stdio.h>
#include <string.h>
#define _D_NAME_MAX 50
#define FROM "/some/local/path/from/"
#define TO "/some/local/path/to/"
char file[_D_NAME_MAX + 1] = {'\0'};
int funMove(char *file, char *from, char *to) {
printf ("[%s] [%s] [%s]\n", file, from, to);
return 0;
}
int main (void) {
strcpy (file, "fspec");
int x = funMove(file, FROM, TO);
printf ("[%d]\n", x);
return 0;
}
It outputs:
[fspec] [/some/local/path/from/] [/some/local/path/to/]
[0]
as expected, so there must be a problem elsewhere if you're seeing to truncated.
Apologies!! Actually, nothing was wrong with the code and the macro didn't get truncated but got overridden. There was another macro with the same name and content except the slash. So, the macro was got replaced instead of the intended one.
#define TO "/some/local/path/to" //header file 1
#define TO "/some/local/path/to/" //header file 2
I just had the header file 2 in mind and misunderstood that the macro got truncated. Actually, the macro from header file 1 was used instead of file 2 which was the intended one.
Thanks for all your answers and support.
I just started to look at C, coming from a java background. I'm having a difficult time wrapping my head around pointers. In theory I feel like I get it but as soon as I try to use them or follow a program that's using them I get lost pretty quickly. I was trying to follow a string concat exercise but it wasnt working so I stripped it down to some basic pointer practice. It complies with a warning conflicting types for strcat function and when I run it, crashes completly.
Thanks for any help
#include <stdio.h>
#include <stdlib.h>
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
strcat(s,t);
}
void strcat(char *s, char *t) {
printf("%s",*s);
}
Your printf() should look like this:
printf("%s",s);
The asterisk is unnecessary. The %s format argument means that the argument should be a char*, which is what s is. Prefixing s with * does an extra invalid indirection.
You get the warning about conflicting types because strchr is a standard library routine, which should have this signature:
char * strcat ( char * destination, const char * source );
Yours has a different return type. You should probably rename yours to mystrchr or something else to avoid the conflict with the standard library (you may get linker errors if you use the same name).
Change
printf("%s",*s);
to
printf("%s",s);
The reason for this is printf is expecting a replacement for %s to be a pointer. It will dereference it internally to get the value.
Since you declared s as a char pointer (char *s), the type of s in your function will be just that, a pointer to a char. So you can just pass that pointer directly into printf.
In C, when you dereference a pointer, you get the value pointed to by the pointer. In this case, you get the first character pointed to by s. The correct usage should be:
printf( "%s", s );
BTW, strcat is a standard function that returns a pointer to a character array. Why make your own?
Replacing *s with s won't append strings yet, here is fully working code :
Pay attention to function urstrcat
#include <stdio.h>
#include <stdlib.h>
/* urstrcat: concatenate t to end of s; s must be big enough */
void urstrcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
urstrcat(s,t);
return 0;
}
void urstrcat(char *s, char *t) {
printf("%s%s",s,t);
}
pointers are variable which points to address of a variable.
#include "stdio.h"
void main(){
int a,*b;
a=10;
b=&a;
printf("%d",b);
}
in the follwing code you will see a int 'a' and a pointer 'b'.
here b is taken as pointer of an integer and declared by giving'' before it.'' declare that 'b' is an pointer.then you will see "b=&a".this means b is taking address of integer "a" which is keeping value 10 in that particular memory and printf is printing that value.
char *test = "hello";
test = change_test("world");
printf("%s",test);
char* change_test(char *n){
printf("change: %s",n);
return n;
}
im trying to pass a 'string' back to a char pointer using a function but get the following error:
assignment makes pointer from integer without a cast
what am i doing wrong?
A function used without forward declaration will be considered having signature int (...). You should either forward-declare it:
char* change_test(char*);
...
char* test = "hello";
// etc.
or just move the definition change_test before where you call it.
printf() prints the text to the console but does not change n. Use this code instead:
char *change_test(char *n) {
char *result = new char[256];
sprintf(result, "change: %s", n);
return result;
}
// Do not forget to call delete[] on the value returned from change_test
Also add the declaration of change_test() before calling it:
char *change_test(char *n);
You're converting an integer to a pointer somewhere. Your code is incomplete, but at a guess I'd say it's that you're not defining change_test() before you use it, so the C compiler guesses at its type (and assumes it returns an integer.) Declare change_test() before calling it, like so:
char *change_test(char *n);
thanks a bunch guys! didnt think i would have this problem solved by lunch. here is the final test class
/* standard libraries */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* change_test(char*);
int main(){
char *test = "hello";
test = change_test("world");
printf("%s",test);
return (EXIT_SUCCESS);
}
char* change_test(char *n){
return n;
}