Skip to content

Instantly share code, notes, and snippets.

@shaunlgs
Last active May 26, 2023 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shaunlgs/11196f2320e9013c000320f6e538a98b to your computer and use it in GitHub Desktop.
Save shaunlgs/11196f2320e9013c000320f6e538a98b to your computer and use it in GitHub Desktop.
Convert char array into int array in C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int intArray[255];
static char charArray[255] = "5 2 -3 4 0 9";
static int numInt = 0;
void charToIntArray() {
char *p;
char temp[10];
int tempIndex = 0;
int intArrayIndex = 0;
int charArrayLen = strlen(charArray);
// Empty the temp char array
for(int j=0; j<10; j++) {
temp[j] = ' ';
}
for(int i=0; i<charArrayLen; i++) {
// Meets a space char
if(charArray[i] == ' ') {
// Convert the temp char array into an integer, and add the integer into integer array
intArray[intArrayIndex] = (int) strtol(temp, &p, 10);
intArrayIndex += 1;
// Empty the temp char array
for(int j=0; j<10; j++) {
temp[j] = ' ';
}
tempIndex = 0;
}
else {
// Record into temp char array
temp[tempIndex] = charArray[i];
tempIndex += 1;
}
}
// Record last integer
intArray[intArrayIndex] = (int) strtol(temp, &p, 10);
intArrayIndex += 1;
numInt = intArrayIndex;
}
int main()
{
charToIntArray();
for(int i=0; i<numInt; i++) {
printf("%d ", intArray[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment