im a beginner and my english is not so well so sorry first. i wrote a function that gets a string and a number, and move every letter in the string 'number' steps. i tried to debug it and it stop working. anyone knows the problem?
here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void moveString(char* str, int _switch);
void main()
{
char arr = "abcdef";
moveString(arr, 2);
printf("%s", arr);
}
void moveString(char* str, int _switch)
{
int len = strlen(str) + 1, i = 0, j = 0, move = len - _switch + 1;
char* temp = (char*)malloc(sizeof(char)*len);
if (!temp)
return NULL;
for (i = 0;i < move;i++)
temp[i+_switch] = str[i];
for (j = 0;j < _switch;j++)
temp[j] = str[len - _switch + j + 1];
str = temp;
}
here is the error:
Exception thrown at 0x0FCA1FD0 (ucrtbased char arr = ".dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0x00000030."
You should pay attention to the compiler warnings and eliminate of all them. They exist for a reason.
When you complie your code, you are most probably getting something like warning: initialization makes integer from pointer without a cast [-Wint-conversion] char arr = "abcdef";
which is the reason for your crash.
It should be char *arr = "abcdef"
, because "abcdef"
in C is a pointer to the area of memory where abcdef
is written.
But that's not the only problem with your program. Seriously, look at the compiler messages and make sure you understand what are the warnings, and fix your code not to produce any.
User contributions licensed under CC BY-SA 3.0