Here\'s a program I wrote to copy a string constant.
When the program is run it crashes. Why is this happening ?
#include
char *alph
cpy function will take two char pointers and the src pointer will point to the initial character of src(char array) defined in the main function, and same as the des pointer will point to the initial location of des(char array) defined in the main function and the while loop value of the src pointer will assign the value to des pointer and increment the pointer to the next element, this will happen until while loop encountered with null and comes out of the loop and des pointer will simply assigned null after taking all the values.
#include<stdio.h>
void cpy(char *src,char *des)
{
while(*(des++) = *(src++));
*des = '\0';
}
int main()
{
char src[100];
char des[100];
gets(src);
cpy(src,des);
printf("%s",des);
}
Output: Image
You can directly do the below code:
char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *l = alpha;
If your code was below:
const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *l = alpha;
:)
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 256
int main(void) {
char *original, *copy, *start; //three character pointers
original = malloc(sizeof(char) * MAX_LENGTH); //assigning memory for strings is good practice
gets(original); //get original string from input
copy = malloc(sizeof(char) * (strlen(original)+1)); //+1 for \0
start = copy;
while((*original)!='\0')
*copy++ = *original++;
*copy = '\0';
copy = start;
printf("The copy of input string is \"%s\".",copy);
return 0;
}
Copy a string "constant/literal/pointer"
char *str = "some string thats not malloc'd";
char *tmp = NULL;
int i = 0;
for (i = 0; i < 6; i++) {
tmp = &str[i];
}
printf("%s\n", tmp);
Reversed
char *str = "some stupid string";
char *tmp, *ptr = NULL;
ptr = str;
while (*str) { ++str; }
int len = str - ptr;
int i = 0;
for (i = len; i > 11; i--) {
tmp = &ptr[i];
}
printf("%s\n", tmp);
tmp = &blah[i]
can be interchanged with tmp = &(*(blah + i))
.
To copy strings in C, you can use strcpy. Here is an example:
#include <stdio.h>
#include <string.h>
const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);
If you want to avoid accidental buffer overflows, use strncpy
instead of strcpy
. For example:
const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
You need to allocate space for l
. Currently it is pointing to a random spot in memory, and if you try to write to that spot, the operating system is likely to shut down (AKA crash) your application. If you want your code to work as is, then assign some space for l
with malloc()
or create l
as an character array with enough space to hold "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
plus the NULL terminator.
See http://cslibrary.stanford.edu/106/ for a primer on pointers.